我有一个如下的文档,现在我想按 channel 、年月和月中的某一天进行分组,然后我想选择当前日期的记录。这是我的文档:
{
"_id" : ObjectId("56de5eab29f9463baf6eb7d2"),
"created_at" : ISODate("2016-03-08T05:10:03.854Z"),
"updated_at" : ISODate("2016-03-08T05:10:03.854Z"),
"channel" : "040403",
"countrycode" : "IN",
"distinctid" : "abc123456",
"os" : "Android"
}
我写了一个这样的聚合:
db.collection.aggregate([
{$project: {
"channel":"$channel",
"year": {$year: "$created_at" },
"month: {$month: "$created_at" },
"day": {$dayOfMonth: "$created_at" }
},
{$match: {
"year": new Date().getFullYear(),
"month": new Date().getMonth() + 1,
"day": new Date().getDate()
},
{$group:
{{"_id":{"channel":"$channel",
year: {$year: "$created_at" },
month: {$month: "$created_at" },
day: {$dayOfMonth: "$created_at" }},
"count":{"$sum":1}
}
}
]
)
但是,它说
missing : after property id @(shell):1:108
我的想法正确吗?为什么语法错误? 谢谢
最佳答案
您的查询有两个问题:
- 每个阶段您都错过了相当多的结束
}
。 - 您按
整数
类型的字段(年
、月
、日
)进行分组,但是您应用需要Date
字段的聚合运算符($year
、$month
、$day
)。
试试这个查询:
db.collection.aggregate([{
$project: {
"channel": "$channel",
"year": { $year: "$created_at" },
"month": { $month: "$created_at" },
"day": { $dayOfMonth: "$created_at" }
}
}, {
$match: {
"year": new Date().getFullYear(),
"month": new Date().getMonth() + 1,
"day": new Date().getDate()
}
}, {
$group: {
"_id": { "channel": "$channel", year: "$year", month: "$month", day: "$day" },
"count": { "$sum": 1 }
}
}]);
关于MongoDB 获取当前日期的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35885180/