MongoDB:使用同一文档中对象的属性重新形成文档
我有一个集合如下,
{
"name": "Sherlock Holmes",
"address": {
"house":"221b",
"street":"Baker St",
"city":"London",
}
},
{
"name": "James Bond",
"address": {
"door_number":"30",
"address1":"Wellington Square",
"city":"London",
}
}
我想在地址
中循环浏览每个属性,并在主文档中创建一个单独的字段。那是在执行命令后,集合应该如下如下,
{
"name": "Sherlock Holmes",
"house":"221b",
"street":"Baker St",
"city":"London",
},
{
"name": "James Bond",
"door_number":"30",
"address1":"Wellington Square",
"city":"London",
}
键
address>地址
对象在不同的文档中有所不同。 使用命令行实现它的最佳方法是什么? 我尝试过以下尝试
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] }
});
}
}
});
,但它仅添加了一个带有名称键
的字段。
I have a collection as follows
{
"name": "Sherlock Holmes",
"address": {
"house":"221b",
"street":"Baker St",
"city":"London",
}
},
{
"name": "James Bond",
"address": {
"door_number":"30",
"address1":"Wellington Square",
"city":"London",
}
}
I would like to loop through each property in address
and create a separate fields in main document. That is after executing the command the collection should look like as follows
{
"name": "Sherlock Holmes",
"house":"221b",
"street":"Baker St",
"city":"London",
},
{
"name": "James Bond",
"door_number":"30",
"address1":"Wellington Square",
"city":"London",
}
The key
of address
object is different for different documents.
What is the best way to achieve it using command line ?
I have tried like below
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] }
});
}
}
});
But it adds a field with name key
only.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
$ MergeObject
构建您的预期输出。然后使用$替换
来解决结果。这是 mongo Playground 供您参考。
You can use
$mergeObjects
to construct your expected output. Then use$replaceRoot
to wrangle the result.Here is the Mongo Playground for your reference.