2015-11-01 140 views
0

組對象我這樣的如何從MongoDB的集合

{ "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字段,因爲我搞砸了語法

回答

2

您需要$group您的文檔由「所有者」然後使用$push accumulator運算符返回文件數組。

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" 
      } 
    ] 
}