如何在mongoDB中按天/月分组?

时间:2018-09-27 03:52:09

标签: mongodb mongodb-query aggregation-framework

这是一个文档的样子:

{
    "login_Id": "c",
    "name": "Abhishek Soni",
    "location": "BLAHBLAH",
    "work": [
        {
            "date":ISODate("2014-01-01"),
            "total_time": 100,
        },
        {
            "date":ISODate("2014-09-02"),
            "total_time": 100,
        },
        {
            "date":ISODate("2014-01-01"),
            "total_time": 10,
        },
    ]
}

我想要做的是运行一个查询,该查询将给出如下输出:

{login_Id: 'c', work:{'01' : 110, '02': 100, ... and so on}}

基本上,我只想将work部分按月分组。

这是我尝试过的:

db.employees.aggregate([
    {
        "$project": {
            "_id": 0,
            "login_Id": 1,
            "time": {
                "$sum": "$work.total_time"
            }
        }
    },
    {
        "$group": {
            "_id": {
                "$dayOfYear": "$work.date"
            },
            "time": {
                "$sum": "$work.total_time"
            }
        }
    }
]);

但是它输出null。如果我删除了group子句,我得到的总金额(即210)出了什么问题?

1 个答案:

答案 0 :(得分:1)

您可以尝试以下汇总

db.collection.aggregate([
  { "$unwind": "$work" },
  { "$match": { "work.date": { "$type": "date" }}},
  { "$group": {
    "_id": { "date": { "$dayOfMonth": "$work.date" }},
    "time": { "$sum": "$work.total_time" },
    "login_Id": { "$first": "$login_Id" }
  }},
  { "$group": {
    "_id": "$login_Id",
    "data": {
      "$push": {
        "k": { "$toString": "$_id.date" },
        "v": "$time"
      }
    }
  }},
  { "$project": {
    "work": { "$arrayToObject": "$data" },
    "_id": 0,
    "login_id": "$_id"
  }}
])

Output

[
  {
    "login_id": "c",
    "work": {
      "1": 110,
      "2": 100
    }
  }
]