Ankit
Ankit

Reputation: 1011

how to rename one element name in entire collection in mongodb

I have a mongoose dataset like this:

{
    "_id" : ObjectId("5a8a91baec129c86c6a30cb6"),
    "sweet" : "APPLE",
    "price" : 27,
    "sellingprice" : 45
}...... like this I have 4000 entry with Different Fruit name.

For some reason, I have to change the "sweet" name to "fruit". For that, I don't know how to update All 4000 entry. Any help is really appreciated. Desired result will be like:

{
    "_id" : ObjectId("5a8a91baec129c86c6a30cb6"),
    "fruit" : "APPLE",
    "price" : 27,
    "sellingprice" : 45
},
{
    "_id" : ObjectId("5a8a91baec129c86c6a30cb7"),
    "fruit" : "BANANA",
    "price" :48,
    "sellingprice" : 59
}and so on upto 3998 entry more.

I know the query where anything add on entire column like this:

db.Collection.update({}, {$set: {'key': 'value'}}, false, true);

But no clue about this. Please suggest some good approach

Upvotes: 0

Views: 58

Answers (1)

Efe
Efe

Reputation: 5796

Use $rename.

db.Collection.update({'sweet': {$exists: true}}, {$rename:{'sweet':'fruit'}}, false, true);
  • First check if sweet field exists
  • Then rename it

Upvotes: 4

Related Questions