Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I rename a field for all documents in MongoDB?

Tags:

mongodb

Assuming I have a collection in MongoDB with 5000 records, each containing something similar to:

{ "occupation":"Doctor", "name": {    "first":"Jimmy",    "additional":"Smith" } 

Is there an easy way to rename the field "additional" to "last" in all documents? I saw the $rename operator in the documentation but I'm not really clear on how to specify a subfield.

like image 775
soulkphp Avatar asked Feb 13 '12 01:02

soulkphp


People also ask

How do I rename a nested field in MongoDB?

If you have nested objects defined in the schema then one can use the below convention to perform rename. db. employee. updateMany({}, {$rename:{"Employee.

Which is the required field for all MongoDB documents?

The _id Field In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field.


1 Answers

You can use:

db.foo.update({}, {$rename:{"name.additional":"name.last"}}, false, true); 

Or to just update the docs which contain the property:

db.foo.update({"name.additional": {$exists: true}}, {$rename:{"name.additional":"name.last"}}, false, true); 

The false, true in the method above are: { upsert:false, multi:true }. You need the multi:true to update all your records.

Or you can use the former way:

remap = function (x) {   if (x.additional){     db.foo.update({_id:x._id}, {$set:{"name.last":x.name.additional}, $unset:{"name.additional":1}});   } }  db.foo.find().forEach(remap); 

In MongoDB 3.2 you can also use

db.students.updateMany( {}, { $rename: { "oldname": "newname" } } ) 

The general syntax of this is

db.collection.updateMany(filter, update, options) 

https://docs.mongodb.com/manual/reference/method/db.collection.updateMany/

like image 141
Felix Yan Avatar answered Sep 22 '22 07:09

Felix Yan