4

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.

Soham
  • 218
  • 2
  • 6
  • 15

2 Answers2

11

There is operator $rename.

db.user.updateMany( {}, { $rename: { "user": "name" } } )
s7vr
  • 73,656
  • 11
  • 106
  • 127
  • How can I copy the ObjectId from Mongoshell ? I am trying to select it, but can't.. Any idea ? – Soham Jan 04 '17 at 18:43
  • you can try something like this. `var cursor = db.user.find(); while (cursor.hasNext()) { var doc= cursor.next(); print( "_id: " + doc._id ); }`. More here https://docs.mongodb.com/manual/tutorial/iterate-a-cursor/ – s7vr Jan 04 '17 at 19:00
  • Thank u so much ! – Soham Jan 04 '17 at 21:23
  • I was trying to add a new embedded document into an existing document. Current document structure is {_id : ObjectId(xxxxxxx), name:"Soham", age:10} . Trying to embed the address document address : { city :"XYZ", zip:1234} into the above document. I did the following steps var a = db.names.find({"name":"Soham"}) ; a.address = {city:"XYZ",zip:1234}; db.names.update({name:"Soham"},a); when I ran it , it threw error. This were the exact steps given in the book by kristina chodorow, so not sure what is going wrong. Kindly let me know if you know the answer. Thanks in advance. – Soham Jan 05 '17 at 01:19
  • This is how you insert embedded document. `db.names.update({name:"Soham"},{ $set: { "address.city": "zzz", "address.zip":1234 } })`. For more info, https://docs.mongodb.com/manual/reference/operator/update/set/. If you see more problems, please create a new question as this doesnt belong here. – s7vr Jan 05 '17 at 01:29
  • Thank u so much, it worked. But not sure why it's not working the way it was referred in the book by Kristina Chodorow. This is the book which was being suggested by MongoDB University – Soham Jan 05 '17 at 01:47
  • okay, just to answer the part from the book. `var a = db.names.findOne({"name":"Soham"}); a.address = {city:"XYZ",zip:1234}; db.names.update({name:"Soham"},a);` find returns cursor and findOne returns doc. – s7vr Jan 05 '17 at 02:08
10

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" } } )
Alex
  • 37,502
  • 51
  • 204
  • 332