在mongodb中按月份和日期分组并显示列表
Posted
技术标签:
【中文标题】在mongodb中按月份和日期分组并显示列表【英文标题】:Group by month and date in mongodb and display the list 【发布时间】:2021-09-21 13:50:31 【问题描述】:我的数据库产品架构结构
"_id" : "507d95d5719dbef170f15bf9" , "name" : "AC3 Series Charger", "type" : "accessory", "price" : 19,"created":"1626083461034"
"_id" : "507d95d5719dbef170f15bfa" , "name" : "AC3 Case Green", "type" : "case" , "price" : 12, "created":"1625805979235"
"_id" : "507d95d5719dbef170f15bfb" , "name" : "Phone Extended Warranty", "type" : "warranty", "price" : 38,"created":"1624374320653"
"_id" : "507d95d5719dbef170f15bfc" , "name" : "AC3 Case Black", "type" : "case" , "price" : 12.5,"created":"1624606153646"
"_id" : "507d95d5719dbef170f15bfd" , "name" : "AC3 Case Red", "type" : "case" , "price" : 12, "created":"1624362066717"
"_id" : "507d95d5719dbef170f15bfe" , "name" : "Phone Service Basic Plan", "type" : "service", "price":9.5,"created":"1624446320186"
"_id" : "507d95d5719dbef170f15bff" , "name" : "Phone Service Core Plan", "type" : "service", "price" :3.5,"created":"1624605403064"
"_id" : "507d95d5719dbef170f15c00" , "name" : "Phone Service Family Plan", "type" : "service", "price":10.4,"created":"1624446320173"
我想获取基于 month and day
的记录,为此,我编写了如下查询
db.collection.aggregate([
"$group":
_id: month: "$month": "$toDate": "$created" , day: "$day" ,
product: "$push": "$name"
])
但它给出了错误
An object representing an expression must have exactly one field: $month: $toDate: \"$created\" , day: \"$day\"
预期输出
month:5
day:12
products:[
"name" : "Phone Service Family Plan"
,
"name" : "Phone Service Core Plan"
]
【问题讨论】:
"$day"
- 您在示例文档中没有该字段。我认为您还可以使用适当的聚合运算符将created
字段转换为day
(我认为有一个$day
聚合运算符)。
【参考方案1】:
您需要先使用 $toLong 将字符串转换为 long 并使用 $dayOfMonth 运算符,因为 MongoDB 中没有 $day
:
db.collection.aggregate([
"$group":
_id:
month: "$month": "$toDate": $toLong: "$created" ,
day: "$dayOfMonth": "$toDate": $toLong: "$created"
,
product:
"$push": "$name"
,
$group:
_id: "$_id.month",
monthDays:
$push:
day: "$_id.day",
product: "$product"
,
$project:
_id: 0,
month: "$_id",
monthDays: 1
,
])
Mongo Playground
【讨论】:
月份数据正在分组。查看第 7 个月的结果 @ram12393 我不完全明白出了什么问题,你能粘贴给定数据的预期结果吗? 此解决方案按(月和日)对(我相信)您所期望的进行分组 如果您查看查询结果,有 7 个月的记录是不同日期的倍数。我的问题是我们如何在单个数组下根据天而不是倍数来做同月记录。 你收到我的问题了吗??以上是关于在mongodb中按月份和日期分组并显示列表的主要内容,如果未能解决你的问题,请参考以下文章
Pandas:在两个不同时间序列中按日期顺序分组在同一 ID 下的列表中显示事件