0

I have an object that looks like the following:

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

I am trying to update the sync field for specific object in the array. So for example if I update the sync field for the object at index 0 or address tz1SUgyRB8T5jXgXAwS33pgRHAKrafsdkjhc by doing the following it yields:

> 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
                }
        ]
}

It works as expected, but if I perform the same update command to switch back sync:false, it gives me a malformed object, while deleting the rest of the array:

> 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 Answers1

0

You can update specific array item, if item match your case using $ operator

 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.
Biplab Malakar
  • 750
  • 6
  • 11