7

How is possible to rename a field in multiples documents in a MongoDB? I have a collections with elements like this, and I want the rename the field "name" by "userName" in all the collection

{
    "name"       : "luisPerez",
    "address"    : "Gaiman",
    "addressFmt" : "Gaiman, Chubut Province, Argentina",
    "loc" : {
        "type" : "Point",
        "coordinates" : [ -65.4920111, -43.2895976  ]
    }, 
}
Pablo Ezequiel Inchausti
  • 16,623
  • 7
  • 28
  • 42

3 Answers3

26

You may use rename operator to rename your fields

db.coll.update({}, {$rename:{"name":"userName"}}, false, true);

false : upsert:false
true : multi:true 
Rahul
  • 15,979
  • 4
  • 42
  • 63
  • In pymongo, this looks like `db.coll.update_many({}, {"$rename": {"name": "userName"}})`, since `update` is deprecated. – Noumenon Sep 03 '21 at 18:17
5

Posible duplicity with:

How can I rename a field for all documents in MongoDB?

Posible use $rename

db.collection({}, {$rename:{"name":"userName"}}, false, true);
Community
  • 1
  • 1
Matej Marconak
  • 1,365
  • 3
  • 20
  • 25
0

You can check this link: https://docs.mongodb.com/manual/reference/operator/update/rename/

It is a new feature of 3.2 - 3.4 . If you have previous version, you have to pass all documents and set new field and after that unset the previous one.

Moi Syme
  • 466
  • 2
  • 8