Reputation: 1046
This is what I have in my db.
{
"_id": { "$oid" : "1111" },
"gallery": {
"images": [
{
"image": "test1.jpg",
"_id": { "$oid" : "1111a" }
},
{
"image": "test2.jpg",
"_id": { "$oid" : "1111b" }
},
{
"image": "test3.jpg",
"_id": { "$oid" : "1111c" }
}
]
}
}
,{
"_id": { "$oid" : "2222" },
"gallery": {
"images": [
{
"image": "test1.jpg",
"_id": { "$oid" : "2222a" }
}
]
}
}
I would like to update the second element (image:"test2.jpg") of the first element (_id:"1111"). The result should be
...
{
"image": "test2new.jpg",
"_id": { "$oid" : "1111b" }
},
...
I have the _id of the second image "1111b". How can I do it?
UPDATE
I tried this query, but it doesn't work.
{
'_id':{'$oid' : '1111' }
,'gallery.image': $elemMatch:{ '_id':{'$oid':'1111b' } }
}
,{
$set:{ 'gallery.images.$.image':'test2new.jpg' }
}
SOLUTION
_id without quotes and without add { "$oid" :
{
{ _id : '1111' }
,{ 'gallery.image': $elemMatch:{ _id:'1111b' } }
}
,{
$set:{ 'gallery.images.$.image':'test2new.jpg' }
}
Upvotes: 1
Views: 3763
Reputation: 886
You can use the $ operator with update.Assuming your collection is named images you can use the following query:
db.images.update({'_id.oid':'1111','gallery.images':{'$elemMatch':{'image':'test2.jpg'}}},{'$set':{'gallery.images.$.image':'test2new.jpg'}})
You can read more about it here : http://docs.mongodb.org/manual/core/update/#update-a-document-element-without-specifying-its-position
Upvotes: 2