我如何按ID和月分组?

时间:2017-07-24 09:00:15

标签: mongodb aggregation-framework

如何在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和日期列的分组进行分组。

1 个答案:

答案 0 :(得分:1)

首先"将您的字符串转换为日期"操作非常简单:

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"像这样,人们将正确地排序数字值。