我们如何更新MongoDB shell中的Array对象值

时间:2018-05-30 18:17:38

标签: mongodb mongodb-query

我想更新我的嵌套数组对象中包含ObjectId的所有MongoDB文档

我的医生是:

{
  "_id" : ObjectId("5a61a6bdae8bdc26685f8c27"), 
  "variant_count" : 1, 
  "salts" : [
    {
        "name" : "Cetirizine", 
        "classification" : "HD", 
        "dosage" : 0.0, 
        "is_cold_storage" : false, 
        "id" : ObjectId("5a61a292ae8bdc26685f2a91")
    }]
  "drug_category" : "DRUGS", 
  "name" : "Adicold Tab", 

}

我想将所有salts.id更新为字符串,

例如。

{
  "_id" : ObjectId("5a61a6bdae8bdc26685f8c27"), 
  "variant_count" : 1, 
  "salts" : [
    {
        "name" : "Cetirizine", 
        "classification" : "HD", 
        "dosage" : 0.0, 
        "is_cold_storage" : false, 
        "id" : "5a61a292ae8bdc26685f2a91"
    }]
  "drug_category" : "DRUGS", 
  "name" : "Adicold Tab", 
}

2 个答案:

答案 0 :(得分:0)

这对我有用:

db.product.find({"salts.id" : {$type : 7}}).forEach(
    function(doc) {
    var salts = doc.salts;
    var newSalts = [];
    if (Array.isArray(salts) && salts.length > 0) {
      for (i = 0; i < salts.length; i++) { 
        salt = salts[i];
        if (salt['id'] != null && typeof salt['id'] == 'object') {
            salt['id'] = salt['id'].str
            newSalts.push(salt)
        } else {
          newSalts.push(salt)
        }
      } 
      db.product.update( { _id: doc._id }, { $set: { salts: newSalts } } 
     );
      i = i + 1;
    }
  }
);

答案 1 :(得分:-1)

**This code is working fine for me.**

db.collectionName.find({}).forEach(function(item){
                    if (item) {
                        item.salts.forEach(function(data){ 
                            if(data){
                                data.id = data.id.valueOf();
                            }
                        })
                        db.collectionName.save(item);
                    }
                })