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

标签 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 字段插入,因为我弄乱了语法

最佳答案

您需要$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"
          }
  ]
}

关于mongodb - 如何对 MongoDB 集合中的对象进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33466221/

相关文章:

mongodb - 查询嵌套组并插入 mongodb

MongoDB Tree Model : Get all ancestors, 获取所有后代

javascript - 从 Mongodb 中检索一个元素

java - 想要创建动态 mongo 查询来接受 DTO 字段

mongodb - Apache Camel 读取 MongoDB 集合 - 不处理任何行

c++ - 编译我的代码以通过 xcode 在 OSX 中使用 mongodb c 驱动程序

mongodb - 使用键值对将 mongo 数组转换为对象

mongodb - 导出集合并用另一个集合中的字段替换字段(聚合?)

mongodb - Reactivemongo 将 map 序列化为 BSONDocument

node.js - 如何在 URL 中传递 MongoDB 集合内文档的 objectID?