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

Awe*_*Cat 2 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"}
Run Code Online (Sandbox Code Playgroud)

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

{
 [{
  "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"}]
 }]
}
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种方法来做到这一点。我尝试过分组和聚合,但我只能将 file_name 字段推入,因为我搞乱了语法

sty*_*ane 5

您需要$group按“所有者”访问您的文档,然后使用$push累加器运算符返回文件数组。

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

返回:

{
  "_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"
          }
  ]
}
Run Code Online (Sandbox Code Playgroud)