如何在MongoDB中按ID和月份分组?
我的数据如下所示:
{
"_id" : ObjectId("597225c62e7cbfc9a0b099f8"),
"LogId" : NumberInt(17351963),
"EntryId" : NumberInt(22),
"Date" : "2013-08-11 00:00:00",
"LogTypeId" : NumberInt(6),
"Count" : NumberInt(1),
"EntryType" : NumberInt(1)
}
{
"_id" : ObjectId("597225c62e7cbfc9a0b099f9"),
"LogId" : NumberInt(17352356),
"EntryId" : NumberInt(23),
"Date" : "2013-08-11 00:00:00",
"LogTypeId" : NumberInt(6),
"Count" : NumberInt(2),
"EntryType" : NumberInt(1)
}
{
"_id" : ObjectId("597225c62e7cbfc9a0b099fa"),
"LogId" : NumberInt(17360483),
"EntryId" : NumberInt(28),
"Date" : "2013-08-11 00:00:00",
"LogTypeId" : NumberInt(6),
"Count" : NumberInt(1),
"EntryType" : NumberInt(1)
}我的简化聚合查询运行时没有错误,但它没有分组:
db.log.aggregate([
{"$group":{"_id":"$EntryId", "Count":{"$sum":"$Count"}}},
{"$sort": {"EntryId": 1}}
])最后,我希望按EntryID和日期列的月份进行分组。
发布于 2017-07-24 17:14:25
首先,通过一个非常简单的操作“将字符串转换为日期”:
let ops = [];
db.log.find().forEach(doc => {
ops.push({ "updateOne": {
"filter": { "_id": doc._id },
"update": { "$set": { "Date": new Date(doc.Date.replace(" ","T")) } }
}});
if ( ops.length >= 500 ) {
db.log.bulkWrite(ops);
ops = [];
}
});
if ( ops.length > 0 ) {
db.log.bulkWrite(ops);
ops = [];
};然后运行新的聚合:
db.log.aggregate([
{ "$group": {
"_id": {
"EntryId": "$EntryId",
"year": { "$year": "$Date" },
"month": { "$month": "$Date" }
},
"Count": { "$sum": 1 }
}},
{ "$sort": { "_id": 1 } }
])还要注意的是,即使是像这样的“复合_id”也会正确地排序到它的数值。
https://stackoverflow.com/questions/45276323
复制相似问题