如何在MongoDB中将多个文档/对象放入一个文档/对象中

jjjwad0x  于 2023-01-25  发布在  Go
关注(0)|答案(2)|浏览(163)

我有一个文档列表,如下所示:

config: {
    _id: ObjectId('63c6a4b858612f44f37d4771'),
    type: "TypeA",
    priority: 1
}

config: {
    _id: ObjectId('627279d3ba7aef5d6418c867'),
    type: "TypeB",
    priority: 3
}

config: {
    _id: ObjectId('628b4d3ff5b1c1736c0b654a'),
    type: "TypeC",
    priority: 4
}

类型是唯一的。是否可以将这些文档合并为一个文档,并将类型作为每个对象字段的键,如下所示:

TypeA: {
    _id: ObjectId('63c6a4b858612f44f37d4771'),
    priority: 1
},
TypeB: {
    _id: ObjectId('627279d3ba7aef5d6418c867'),
    priority: 3
},
TypeC: {
    _id: ObjectId('628b4d3ff5b1c1736c0b654a'),
    priority: 4
}

我试过这样的方法:

{
    $project: {
        newDoc: [ 
            {
                k:'$config.type', 
                v: {
                    id:'$config._id', 
                    priority: '$config.priority'
                }
            }
        ]
    }
}, {
    '$replaceRoot': {
        'newRoot': {
            '$arrayToObject': '$newDoc'
        }
    }
}

这样我得到的文档如下所示:

TypeA: {
    _id: ObjectId('63c6a4b858612f44f37d4771'),
    priority: 1
}

TypeB: {
    _id: ObjectId('627279d3ba7aef5d6418c867'),
    priority: 3
}

TypeC: {
    _id: ObjectId('628b4d3ff5b1c1736c0b654a'),
    priority: 4
}

但我需要将这些合并到一个文档中...

ecr0jaav

ecr0jaav1#

一个选项是$group和使用$arrayToObject

db.collection.aggregate([
  {$group: {
      _id: null,
      data: {
        $push: {
          k: "$config.type",
          v: {_id: "$config._id", priority: "$config.priority"}
        }
      }
  }},
  {$replaceRoot: {newRoot: {$arrayToObject: "$data"}}}
])

了解它在playground example上的工作原理

6tdlim6h

6tdlim6h2#

您可以尝试以下聚合:

db.collection.aggregate([
   {
      $group: {
         _id: null,
         activeConfigs: {$push: '$$ROOT'},
      }
   }
])

结果应该给予:

[
   {
     _id: null,
     activeConfigs: [
        TypeA: {
           _id: ObjectId('63c6a4b858612f44f37d4771'),
           priority: 1
        },
        TypeB: {
           _id: ObjectId('627279d3ba7aef5d6418c867'),
           priority: 2
        },
        TypeC: {
           _id: ObjectId('628b4d3ff5b1c1736c0b654a'),
           priority: 5
        }
     ]
   }
]

相关问题