25

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 ?

JuanPablo
  • 23,792
  • 39
  • 118
  • 164

3 Answers3

50

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"}})
Mark Stosberg
  • 12,961
  • 6
  • 44
  • 49
Sammaye
  • 43,242
  • 7
  • 104
  • 146
4
db.collectionname.update( { "field" : "oldvalue" }, { $set:{ "field" : "newvalue" } }, { multi : true } );
abdulH
  • 375
  • 1
  • 6
  • 19
2

Since MongoDB 3.2, you can use this shorter syntax:

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

Mark Stosberg
  • 12,961
  • 6
  • 44
  • 49
Josh
  • 21
  • 4