I try rename one field in all documents of a collection, with
db.coll.update({},{ $rename: {'originField':'newField'} });
but only one document is changed, why ?
MongoDB's update() and save() methods are used to update document into a collection.
Definition. Modifies an existing document or documents in a collection. The method can modify specific fields of an existing document or documents or replace an existing document entirely, depending on the update parameter.
All updates in MongoDB are, by default, singular. You must add a third option to your command to make:
db.coll.update({},{ $rename: {'originField':'newField'} }, {multi:true});
If you are using 3.2 and above you can use updateMany()
:
db.coll.updateMany({}, {$rename: {'originField': "newField"}})
db.collectionname.update( { "field" : "oldvalue" }, { $set:{ "field" : "newvalue" } }, { multi : true } );
Since MongoDB 3.2, you can use this shorter syntax:
db.coll.updateMany({}, {$rename: {'originField': "newField"}})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With