Setting value of a specific child element mongodb -
i have following database:
> db.test.find().pretty() { "_id" : objectid("56b4c13d7db9acd913ce6e08"), "state" : "helloworld", "items" : [ { "guid" : 123, "uniqueid" : 0 }, { "guid" : 124, "uniqueid" : 1 } ] }
and want set guid
of items.uniqueid = 1
field 125, result 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 part (items of items.guid) traverse element ({items: [ { guid: 123.0, uniqueid: 0.0 }, { guid: 124.0, uniqueid: 1.0 } ]})" } })
what doing wrong?
apply $set
operator $
positional operator in update change guid
field. $
positional operator identify correct element in array update without explicitly specifying position of element in array, final update statement should like:
db.collection.update({ "items.uniqueid": 1 }, { "$set": { "items.$.guid": 125 } } )
if want increment value 1, use $inc
update operator
db.collection.update({ "items.uniqueid": 1 }, { "$inc": { "items.$.guid": 1 } } )
Comments
Post a Comment