Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

db.collection.update( ) all documents

Tags:

rename

mongodb

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 ?

like image 357
JuanPablo Avatar asked Mar 26 '13 23:03

JuanPablo


People also ask

Which method is used to update documents into a collection?

MongoDB's update() and save() methods are used to update document into a collection.

What is the result of DB Collection Update ()?

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.


3 Answers

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"}})
like image 196
Sammaye Avatar answered Dec 10 '22 04:12

Sammaye


db.collectionname.update( { "field" : "oldvalue" }, { $set:{ "field" : "newvalue" } }, { multi : true } );
like image 31
abdulH Avatar answered Dec 10 '22 06:12

abdulH


Since MongoDB 3.2, you can use this shorter syntax:

db.coll.updateMany({}, {$rename: {'originField': "newField"}})

like image 39
Josh Avatar answered Dec 10 '22 06:12

Josh