如何从MongoDB集合中对对象进行分组

时间:2015-11-01 19:24:31

标签: mongodb mongodb-query aggregation-framework

我有像这样的文档集

{ "owner": "550511223", "file_name": "55234OT01", "file_type": "other", "comment": "Just fix it"},
{ "owner": "550510584", "file_name": "55584RS01", "file_type": "resume", "comment": "Good enough"},
{ "owner": "550511223", "file_name": "55234AP01", "file_type": "applicant", "comment": "This will do"}

我需要一个像这样的对象的结果

{
 [{
  "owner" : "550510584",
  "files" : [{"file_name": "55584RS01","file_type": "resume","comment": "Good enough"}],
 },{
  "owner" : "550511234",
  "files" : [{"file_name": "55234AP01","file_type": "applicant","comment": "This will do"},
             {"file_name": "55234OT01","file_type": "other","comment": "Just fix it"}]
 }]
}

我找到了办法。我尝试了分组和聚合,但我只能推送file_name字段,因为我搞乱了语法

1 个答案:

答案 0 :(得分:2)

您需要{"所有者" $group您的文件然后使用$push累加器运算符返回文件数组。

db.collection.aggregate([
    { "$group": {
        "_id": "$owner", 
        "files": { 
            "$push": { 
                "file_name": "$file_name", 
                "file_type": "$file_type", 
                "comment": "$comment" 
            }
         } 
    } }
])

返回:

{
  "_id" : "550510584",
  "files" : [
          {
                  "file_name" : "55584RS01",
                  "file_type" : "resume",
                  "comment" : "Good enough"
          }
  ]
},

{
  "_id" : "550511223",
  "files" : [
          {
                  "file_name" : "55234OT01",
                  "file_type" : "other",
                  "comment" : "Just fix it"
          },
          {
                  "file_name" : "55234AP01",
                  "file_type" : "applicant",
                  "comment" : "This will do"
          }
  ]
}