【发布时间】:2018-04-10 02:38:46
【问题描述】:
我的 cmets 架构具有 createdAt 字段
{
"_id" : ObjectId("5acafcf834d81a1650a35b8c"),
"createdAt" : ISODate("2018-04-09T05:41:12.228Z"),
"author" : ObjectId("5ac8ba3582c2345af70d4658"),
"comment" : "rgeregfedsagvdfsae",
}
{
"_id" : ObjectId("5acafcee34d81a1650a35b8b"),
"createdAt" : ISODate("2018-04-09T05:41:02.992Z"),
"author" : ObjectId("5ac8ba3582c2345af70d4658"),
"comment" : "dsfsfdssfdsfdsf",
}
{
"_id" : ObjectId("5acb024134d81a1650a35b8d"),
"createdAt" : ISODate("2018-04-10T06:03:45.625Z"),
"author" : ObjectId("5ac8ba3582c2345af70d4658"),
"comment" : "dsfdsafdafsdf",
}
我想按createdAt 分组...这应该是我的输出
[ { createdAt: '2018-04-09', numberOfComments: 2 },
{ createdAt: '2018-04-10', numberOfComments: 1 } ]
这个我试过了……
const CommentsCount = await Comment.aggregate([
{
$project:
{
month: { $dateToString: { format: "%Y-%m-%d", date: "$createdAt" } },
}
},
{
$group: {
_id: '$month'
}
}
])
给[ { _id: '2018-04-09' }, { _id: '2018-04-10' } ]
【问题讨论】:
-
createAt 字段的时区部分在所有文档中都不同,我不认为你想要的结果是可能的
-
@0.sh 我觉得有可能
-
查看更新后的问题
-
您忘记在
$group中包含计数聚合,即{ $group: { _id: '$month', numberOfComments: { '$sum': 1 } } } -
@AshishChoudhary 检查以下答案
标签: node.js mongodb mongoose mongodb-query aggregation-framework