MongoDB renaming a field/key

12.1k views Asked by At

I want to change a field name ( just the field name but not the value ) in a document in MongoDB. The document looks like this ( below) and it has only one document in the collection of user= Soham :

{_id : ObjectId(xxxxxxxxxxxx),
 user : "Soham",
 age  : 29
}

Now I want to change the field named 'user' to 'name', but not the value of the field. So in the mongo shell I wrote the below commands:

var soh = db.user.find({"user":"Soham"});
soh.name = soh.user;
delete soh.user;
db.user.update({"user":"Roshan"},soh);

When I am running the update command, it's throwing me error. Not sure where I am going wrong as I am new to MongoDB. Any kind of help is appreciated.

2

There are 2 answers

7
s7vr On BEST ANSWER

There is operator $rename.

db.user.updateMany( {}, { $rename: { "user": "name" } } )
2
Alex On

Use $rename operator.

So, in mongo shell, to update a single document:

db.user.update( { _id: ObjectId(xxxxxxxxxxxx) }, { $rename: { 'user': 'name'} } )

to update all documents

db.user.updateMany( {}, {$rename: { "user": "name" } } )