mongo查询聚合2个文档2个日期

时间:2016-07-22 09:03:02

标签: mongodb mongodb-query aggregation-framework

我有以下收集......

[{
   "_id":"abcd1234",
    "Date" :{"$date":1430418601000},

    "Count":{
        "hr1":0,
        "hr2":20,
        "hr3":1,
        "hr4":4,
        "hr5":0,
      }
},
{
   "_id":"abcd1234",
   "Date" :{"$date":1430505001000},
   "Count":{
       "hr1":2,
       "hr2":15,
       "hr3":15,
       "hr4":0,
       "hr5":1,
}
}
]

我想汇总这些日期的计数,所以总计数就像......

{"hr1":2,
 "hr2":35,
 "hr3":16,//......so on
}

mongodb有可能吗?我不太了解mongo,如果有人可以指导我这个查询会有帮助...

1 个答案:

答案 0 :(得分:0)

运行以下聚合管道应该可以获得所需的结果:

db.collection.aggregate([
    {
        "$group": {
            "_id": null,
            "hr1": { "$sum": "$Count.hr1" },
            "hr2": { "$sum": "$Count.hr2" },
            "hr3": { "$sum": "$Count.hr3" },
            "hr4": { "$sum": "$Count.hr4" },
            "hr5": { "$sum": "$Count.hr5" }
        }
    }
])

指定_id null值将计算所有输入文档的累计值。