对象数组MongoDb中的更新字段

时间:2018-11-15 02:25:23

标签: mongodb

我有一个类似于以下内容的对象:

> db.delegate_list.find({"name": "delegateList"}).pretty()
{
        "_id" : ObjectId("5becd1e0adeb2717c087cec5"),
        "name" : "delegateList",
        "delegates" : [
                {
                        "address" : "tz1SUgyRB8T5jXgXAwS33pgRHAKrafsdkjhc",
                        "sync" : false
                },
                {
                        "address" : "tz1MecudVJnFZN5FSrriu8ULz2d6dDTR7KaM",
                        "sync" : false
                }
        ]
}

我正在尝试更新数组中特定对象的同步字段。因此,例如,如果我通过执行以下操作更新索引为0或地址为tz1SUgyRB8T5jXgXAwS33pgRHAKrafsdkjhc的对象的同步字段,则会产生:

> db.delegate_list.update({"name":"delegateList"}, {$set:{"delegates.0.sync": true}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.delegate_list.find({"name": "delegateList"}).pretty()
{
        "_id" : ObjectId("5becd1e0adeb2717c087cec5"),
        "name" : "delegateList",
        "delegates" : [
                {
                        "address" : "tz1SUgyRB8T5jXgXAwS33pgRHAKrafyg87Yc",
                        "sync" : true
                },
                {
                        "address" : "tz1MecudVJnFZN5FSrriu8ULz2d6dDTR7KaM",
                        "sync" : false
                }
        ]
}

它可以按预期工作,但是如果我执行相同的更新命令以切换回sync:false,它会给我一个畸形的对象,同时删除数组的其余部分:

> db.delegate_list.update({"name":"delegateList"}, {$set:{"delegates.0.sync": false}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.delegate_list.find({"name": "delegateList"}).pretty()
{
        "_id" : ObjectId("5becd1e0adeb2717c087cec5"),
        "name" : "delegateList",
        "delegates" : {
                "address" : "tz1SUgyRB8T5jXgXAwS33pgRHAKrafyg87Yc",
                "sync" : true,
                "0" : {
                        "sync" : false
                }
        }
}

1 个答案:

答案 0 :(得分:0)

如果项目符合您的情况,则可以使用$运算符来更新特定的数组项目

 db.delegate_list.update({"delegates.address":"tz1SUgyRB8T5jXgXAwS33pgRHAKrafyg87Yc"}, {$set:{"delegates.$.sync": false}})

  It will update the sync filed which address is "tz1SUgyRB8T5jXgXAwS33pgRHAKrafyg87Yc" 
  only, and not going to add any extra field.