How do I rename a nested key in mongodb

2019-05-22 20:44发布

问题:

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}

回答1:

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



回答2:

Your question is unclear but it seems you'd like to rename a field name within an array.

The short answer is you can't. As stated in the docs, $rename doesn't expand arrays to find a matching name. It only works on top level fields.

What you can do to simulate rename is by copying the field and its data to the new name, and then deleting the original field. You might also need a way to account for potentially concurrent writes if you have a lot of writes to that object/field.