如何重命名mongodb中的嵌套密钥 [英] How do I rename a nested key in mongodb
问题描述
通常它的工作原理就像这样 db.update({'_ id':id },{$ rename:{'oldfieldname':newfieldname}})
我的文档结构如下
{
'data':'.....',
'field':{'1':{'data ':....},'2':{'data'...}},
'more_data':'....',
}
如果我想在字段1中设置
a新字段我做 db.update({'_ id ':id},{$ set:{'field.0.1.name':'peter'}})
是'field'.1.2.name'
我以为重命名应该是相似的,但它不是...(如 $重命名:{'field'.0.1':2}
这是一个灵活的重命名方法数据库中的键
给出这样的文档结构...
{
_id:ObjectI d(4ee5e9079b14f74ef14ddd2f),
code:130.4,
description:4Socket Plug,
technicalData:{
否:50,
length:200mm,
diameter:20mm
},
}
我想循环遍历所有文档,并将technicalData [Drawing No]重命名为technicalData [图纸号]
在执行面板中运行以下JavaScript(优秀) RockMongo
function remap(x){
dNo = x.technicalData [Drawing No ];
db.products.update({_ id:x._id},{
$ set:{technicalData.Drawing Number:dNo},
$ unset:{technicalData绘图否:1}
});
}
db.products.find({technicalData.Drawing No:{$ ne:null}})。forEach(remap);
代码也将在一个mongo shell中运行
I want rename to rename my dict key in mongodb.
normally it works like that db.update({'_id':id},{$rename:{'oldfieldname':newfieldname}})
My document structure looks like that
{
'data':'.....',
'field':{'1':{'data':....},'2':{'data'...}},
'more_data':'....',
}
if i want to set
a new field in field 1 i do db.update({'_id':id},{$set:{'field.0.1.name':'peter'}})
for field two it is 'field'.1.2.name'
i thought with the rename it should be similar but it isn't ... (like $rename:{'field'.0.1': 2}
Here's a flexible method for renaming keys in a database
Given a document structure like this...
{
"_id": ObjectId("4ee5e9079b14f74ef14ddd2f"),
"code": "130.4",
"description": "4'' Socket Plug",
"technicalData": {
"Drawing No": "50",
"length": "200mm",
"diameter: "20mm"
},
}
I want to loop through all documents and rename technicalData["Drawing No"] to technicalData["Drawing Number"]
Run the following javascript in the execute panel in (the excellent) RockMongo
function remap(x){
dNo = x.technicalData["Drawing No"];
db.products.update({"_id":x._id}, {
$set: {"technicalData.Drawing Number" : dNo},
$unset: {"technicalData.Drawing No":1}
});
}
db.products.find({"technicalData.Drawing No":{$ne:null}}).forEach(remap);
The code will also run in a mongo shell
这篇关于如何重命名mongodb中的嵌套密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!