我有一个如下的集合
{
"name": "Sherlock Holmes",
"address": {
"house":"221b",
"street":"Baker St",
"city":"London",
}
},
{
"name": "James Bond",
"address": {
"door_number":"30",
"address1":"Wellington Square",
"city":"London",
}
}
我想遍历address
中的每个属性,并在主文档中创建一个单独的字段。在执行命令之后,集合应该如下所示
{
"name": "Sherlock Holmes",
"house":"221b",
"street":"Baker St",
"city":"London",
},
{
"name": "James Bond",
"door_number":"30",
"address1":"Wellington Square",
"city":"London",
}
不同文档address
对象的key
不同。使用命令行实现它的最佳方法是什么?我试过如下
db.employees.find().forEach(function(obj) {
for (var key in obj.address) {
if (obj.address.hasOwnProperty(key)) {
db.employees.update({ '_id': obj._id }, {
'$set': { key: obj.address[key] }
});
}
}
});
但是它只添加了一个名称为key
的字段。
您可以使用$mergeObjects
来构造您期望的输出。然后使用$replaceRoot
来调整结果。
db.collection.update({},
[
{
"$addFields": {
"merged": {
"$mergeObjects": [
{
// fields that you want to keep in outer
_id: "$_id",
name: "$name"
},
"$address"
]
}
}
},
{
"$replaceRoot": {
"newRoot": "$merged"
}
}
],
{
multi: true
})
这是Mongo Playground供您参考。