David
David

Reputation: 1494

Setting value of a specific child element mongodb

I have the following database:

> db.test.find().pretty()
{
    "_id" : ObjectId("56b4c13d7db9acd913ce6e08"),
    "state" : "helloworld",
    "items" : [
        {
            "guid" : 123,
            "uniqueId" : 0
        },
        {
            "guid" : 124,
            "uniqueId" : 1
        }
    ]
}

and I want to set the guid of the items.uniqueId = 1 field to 125, so that the result will be:

{
    "_id" : ObjectId("56b4c13d7db9acd913ce6e08"),
    "state" : "helloworld",
    "items" : [
        {
            "guid" : 123,
            "uniqueId" : 0
        },
        {
            "guid" : 125,
            "uniqueId" : 1
        }
    ]
}

I tried:

> db.test.update( {'items.uniqueId' : 1} , { $set : { 'items.guid' : 125 }} )
WriteResult({
    "nMatched" : 0,
    "nUpserted" : 0,
    "nModified" : 0,
    "writeError" : {
        "code" : 16837,
        "errmsg" : "cannot use the part (items of items.guid) to traverse the element ({items: [ { guid: 123.0, uniqueId: 0.0 }, { guid: 124.0, uniqueId: 1.0 } ]})"
    }
})

What am I doing wrong?

Upvotes: 1

Views: 49

Answers (1)

chridam
chridam

Reputation: 103375

Apply the $set operator together with the $ positional operator in your update to change the guid field. The $ positional operator will identify the correct element in the array to update without explicitly specifying the position of the element in the array, thus your final update statement should look like:

db.collection.update({ "items.uniqueId": 1 }, 
    {
        "$set": {
            "items.$.guid": 125
        }
    }
)

If you want to increment the value by 1, use the $inc update operator

db.collection.update({ "items.uniqueId": 1 }, 
    {
        "$inc": {
            "items.$.guid": 1
        }
    }
)

Upvotes: 1

Related Questions