MongoDb从数组更新多个对象

时间:2019-02-28 13:04:24

标签: arrays mongodb

我有一个包含以下字段的文档:

{
  "_id": 1,
  "codes": [
    {"name": "code1", "active": null, "disabled": false},
    {"name": "code2", "active": null, "disabled": false},
    {"name": "code3", "active": null, "disabled": false},
    {"name": "code4", "active": null, "disabled": false},
    {"name": "code5", "active": null, "disabled": false},
    {"name": "code6", "active": null, "disabled": false}
  ]
}

有什么方法可以更新name值等于“ code2”,“ code3”和“ code4”的对象?

例如:

db.collection.update(
  {"_id": 1},
  {
    $set: {
      "codes": [
        {"name": "code2", "active": false, "disabled": true},
        {"name": "code3", "active": true, "disabled": false},
        {"name": "code4", "active": null, "disabled": true}
      ]
    }
  }
)

预期结果:

{
  "_id": 1,
  "codes": [
    {"name": "code1", "active": null, "disabled": false},
    {"name": "code2", "active": false, "disabled": true},
    {"name": "code3", "active": true, "disabled": false},
    {"name": "code4", "active": null, "disabled": true},
    {"name": "code5", "active": null, "disabled": false},
    {"name": "code6", "active": null, "disabled": false}
  ]
}

实际结果:

{
  "_id": 1,
  "codes": [
    {"name": "code2", "active": false, "disabled": true},
    {"name": "code3", "active": true, "disabled": false},
    {"name": "code4", "active": null, "disabled": true}
  ]
}

2 个答案:

答案 0 :(得分:1)

您无法在一个查询中实现此目的,但是您可以循环执行更新数组,并针对代码数组中的元素匹配条件执行更新:

var updatesArray = [
    {"name": "code2", "active": false, "disabled": true},
    {"name": "code3", "active": true, "disabled": false},
    {"name": "code4", "active": null, "disabled": true}
  ]

updatesArray.forEach(function(newCode){
  db.getCollection("collection").update(
    {_id:1},   
    {$set:{
      "codes.$[subcode].active":newCode.active,
      "codes.$[subcode].disabled":newCode.disabled}
    },   
    { multi: true,
       arrayFilters: [ { "subcode.name": newCode.name } ]
    }
  )
})

答案 1 :(得分:0)

使用此命令来实现

public static Cursor getContactList(ContentResolver cr) {
        // reading all data in descending order according to DATE
        Cursor curContact =  cr.query(ContactsContract.Contacts.CONTENT_URI,
                null, null, null, null);
        return curContact;
    }