我的收藏中有一个如下的时间字段。
"time" : NumberLong(1531958400000)
我首先想按当年查询文档(使用 $match),然后获取每个月的文档计数。 我已成功使用以下查询匹配年份。
db.myCollection.aggregate([
{$project: {
year: { "$year":{"$add":[new Date(0),"$time"]}}
}
},
{$match: {year: 2021}}
])
如何为上述场景编写 mongodb 查询? 预先感谢!
您可以执行以下操作:
$date
$group
通过 $month
值来获取计数db.collection.aggregate([
{
"$addFields": {
"parsedDate": {
"$toDate": "$time"
}
}
},
{
"$addFields": {
"year": {
$year: "$parsedDate"
},
"nowYear": {
$year: new Date()
}
}
},
{
$match: {
$expr: {
$eq: [
"$year",
"$nowYear"
]
}
}
},
{
$group: {
_id: {
"$month": "$parsedDate"
},
count: {
$sum: 1
}
}
}
])
这里是Mongo游乐场供您参考。