MongoDB Aggregate, Project and Match



我已经创建了一个聚合查询,以检索按年份分组的记录及其计数。

我当前的查询

db.records.aggregate([
{"$project": {"_id": 0, "date": {"$dateFromString": {"format": "%Y-%m-%d", "dateString": "$when"}}}},
{"$group": {"_id": {"$year": "$date"}, "count": {"$sum": 1}}},
{"$sort": {"_id": 1}}
])

我的收藏

{
"id": "123456", 
"when": "2021-01-01"
}

如何更改当前查询以检索给定年份中的所有记录及其计数,并按月份分组?

样本输出

[{'_id': 01, 'count': 15}, {'_id': 02, 'count': 53}, {'_id': 03, 'count': 64}, {'_id': 04, 'count': 44}, {'_id': 05, 'count': 42}, {'_id': 06, 'count': 129}, {'_id': 07, 'count': 170}, {'_id': 08, 'count': 148}, {'_id': 09, 'count': 67}, {'_id': 10, 'count': 67}, {'_id': 11, 'count': 67}, {'_id': 12, 'count': 50}]

您实际上走在了正确的轨道上。将日期字符串转换为日期后,只需使用$year进行筛选,并使用$group中的$month进行分组和计数。

db.collection.aggregate([
{
"$project": {
"_id": 0,
"date": {
"$dateFromString": {
"format": "%Y-%m-%d",
"dateString": "$when"
}
}
}
},
{
"$match": {
$expr: {
$eq: [
{
"$year": "$date"
},
2021
]
}
}
},
{
$group: {
_id: {
$month: "$date"
},
count: {
$sum: 1
}
}
}
])

这是Mongo游乐场供您参考。

有一点需要注意:将日期存储为字符串被认为是反模式的,会使查询变得不必要的复杂。建议将它们存储为适当的日期字段。

最新更新