Ashish Bagaddeo
Ashish Bagaddeo

Reputation: 39

MongoDB: Rename Field in A Collection (Document and Subdocuments)

Using MongoDB 3.6 I have document structure like below `

{
    "_id" : ObjectId("5d88"),
    "Equipments" : [ 
        {
            "InnerEquipments" : {
                "AssetId" : 678
            },
            "AssetID" : 456
        }
    ],
    "AssetID" : 123
}

I want rename the field from AssetID/AssetId to Asset_ID at all levels. How can I do this with mongo shell.

Upvotes: 1

Views: 410

Answers (2)

Sagar Chaudhary
Sagar Chaudhary

Reputation: 1393

You need to make a script for this.
I have not tested it. Make changes accordingly.

db.collection.find({}).forEach(function(doc) {
    if(doc['AssetID']) {
      doc['Asset_ID'] = doc['AssetID'];
      delete doc['AssetID'];
    } else if (doc['AssetId']) {
      doc['Asset_ID'] = doc['AssetId'];
      delete doc['AssetId']
    }
    if(doc.Equipments && doc.Equipments.length) {
      doc.Equipments.forEach(function(rec) {
        if(rec['AssetID']) {
          rec['Asset_ID'] = rec['AssetID'];
          delete rec['AssetID'];
        } else if (rec['AssetId']) {
          rec['Asset_ID'] = rec['AssetId'];
          delete rec['AssetId']
        }

        if(rec['InnerEquipments']['AssetID']) {
          rec['InnerEquipments']['Asset_ID'] = rec['InnerEquipments']['AssetID'];
          delete rec['InnerEquipments']['AssetID'];
        } else if (rec['InnerEquipments']['AssetId']) {
          rec['InnerEquipments']['Asset_ID'] = rec['InnerEquipments']['AssetId'];
          delete rec['InnerEquipments']['AssetId']
        }
      })
    }
    db.collection.update({'_id':doc._id},doc);
  });

Upvotes: 1

Himanshu Sharma
Himanshu Sharma

Reputation: 3010

The following code can do the trick:

// Getting all documents from the collection
var data = db.collection.find({},{"_id":0}).toArray();

// Converting the data into JSON string
var string = JSON.stringify(data);

// Replacing all variations of assetid with Asset_ID
string = string.replace(/assetid/ig,"Asset_ID");

// Removing existing documents from collection
db.collection.remove({});

// Converting the string back to JSON array and inserting it into the DB
db.collection.insertMany(JSON.parse(string));

Before:

{
    "_id" : ObjectId("5d89e9ab0558a18dd9cfc03a"),
    "Equipments" : [ 
        {
            "InnerEquipments" : {
                "AssetId" : 678
            },
            "AssetID" : 456
        }
    ],
    "AssetID" : 123
}

After:

{
    "_id" : ObjectId("5d89eea80558a18dd9cfc03b"),
    "Equipments" : [
        {
            "InnerEquipments" : {
                "Asset_ID" : 678
            },
            "Asset_ID" : 456
        }
    ],
    "Asset_ID" : 123
}

Upvotes: 1

Related Questions