MongoDB:重命名集合中的字段(文档和子文档)

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

使用MongoDB 3.6 我有如下的文件结构 `

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

我想在所有级别将字段从 AssetID/AssetId 重命名为 Asset_ID。 我怎样才能用 mongo shell.

以下代码可以解决问题:

// 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));

之前:

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

之后:

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

你需要为此制作一个脚本。
我没有测试过。相应地进行更改。

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);
  });