Mongo聚合多个不同

时间:2015-05-29 12:44:46

标签: mongodb

我想重构一个旧的php/mongo代码以使用MongoDB's聚合功能。 现在,我正在做很多查询以提取我想要的数据。

这是文档模型:

{
  "_id" : ObjectId("548eb89c7a9a83fc0000002c"),
  "session" : "870922750",
  "id_category" : 1118,
  "id_subcategory" : 2453,
  "date_created" : ISODate("2014-12-15T12:31:55Z")
}

而且,我需要按每天不同的session字段和subcategory点数汇总数据。 据我所知,回报应该是这样的:

id_subcategory
days
  day 
  count (distinct session)

  day
  count (distinct session)

我已阅读有关$push$addtoset的内容,但我认为我错过了关于聚合如何运作的大图?

谢谢!

1 个答案:

答案 0 :(得分:0)

根据我的理解,我创建了一些示例数据集如下:

db.collectionName.insert([{"session" : "870922750", "id_category" : 1118, "id_subcategory" : 2453, "date_created" : ISODate("2014-12-15T12:31:55Z") },
{"session" : "870922750", "id_category" : 1118, "id_subcategory" : 2453, "date_created" : ISODate("2014-12-15T12:31:55Z") },
{"session" : "870922750", "id_category" : 1118, "id_subcategory" : 2453, "date_created" : ISODate("2014-12-16T12:31:55Z") },
{"session" : "870922751", "id_category" : 1118, "id_subcategory" : 2453, "date_created" : ISODate("2014-12-16T12:31:55Z") },
{"session" : "870922751", "id_category" : 1118, "id_subcategory" : 2454, "date_created" : ISODate("2014-12-16T12:31:55Z") }])

已使用mong aggregation并且根据数据集date_createdISODate,并且ISODateday找出date的{​​{1}},因此请查看日期在汇总$project中使用$dayOfMonth

聚合查询为:

db.collectionName.aggregate({
  "$project": {
    "id_subcategory": 1,
    "session": 1,
    "day": {
      "$dayOfMonth": "$date_created" //find day of given ISODate
    }
  }
}, {
  "$group": {
    "_id": {
      "subCategory": "$id_subcategory", //groups subCategory, session and day 
      "session": "$session",
      "day": "$day"
    },
    "count": {
      "$sum": 1
    }
  }
}, {
  "$group": //this groups required to combining data 
  {
    "_id": "$_id.subCategory",
    "days": {
      "$push": {
        "day": "$_id.day",
        "count": "$count",
        "session": "$_id.session"
      }
    }
  }
}).pretty()