MongoDB Aggregate的多个分组

时间:2017-01-26 05:22:09

标签: javascript mongodb

给出以下Event对象的数据集:

[
    {
        "_id": ObjectId("4fda05cb322b1c95b531ac26",
        "title": "BUTTON CLICKED",
        "createdAt": ISODate("2017-01-12T01:00:00+01:00")
    },
    {
        "_id": ObjectId("1235h1k235h1kl325h1v31gv",
        "title": "BUTTON CLICKED",
        "createdAt": ISODate("2017-01-14T01:00:00+01:00")
    },
    {
        "_id": ObjectId("c2n890904cn897qnxp23hjk1",
        "title": "PAGE VIEWED",
        "createdAt": ISODate("2017-01-12T02:00:00+01:00")
    }
]

我如何按日期按名称对它们进行分组?

期望的结果如下所示:

[ 
  { 
    _id: { year: 2017, month: 1, day: 11 },
    events: [ { 
                title: "BUTTON PRESSED",
                count: 3
               }, { 
                title: "PAGE VIEWED",
                count: 2
               }
            ] 
  },
  { 
    _id: { year: 2017, month: 1, day: 24 },
    events: [ { 
                title: "BUTTON PRESSED",
                count: 1
               }
            ] 
  }
]

非常感谢有关此问题的任何帮助,谢谢!

1 个答案:

答案 0 :(得分:1)

您可以尝试此查询

db.collectionName.aggregate([
    $group: {
       _id : {
        year : { $year : "$createdAt" },
        month : { $month : "$createdAt" },
        day : { $dayOfMonth : "$createdAt" },
        title: "$title"
       },
       count:{$sum:1}
      }
    },
  {
    $group:{
      _id:{
        year: "$_id.year",
        month: "$_id.month",
        day: "$_id.day"
      },
      data:{
        $push: {
          name:"$_id.title",
          count:"$count"
        }
      }
    }
  }
])