Reputation: 103
I have a collection named test looks like the following json:
{
'_id':ObjetcId("..."),
'a':[
{
id:1,
a1:[{x:1,y:1},{x:10,y:11},{x:10,y:12}],
flag:1
},
{
id:2
a1:[{x:1,y:1},{x:10,y:11},{x:10,y:12}],
flag:0
},
]
}
Now I want to push an another ({x:99,y:99})
element into a.a1
with condition that a.id=1
, I tried the command:
db.test.update({'_id':ObjectId('...')},{"$push":{"a.a1":{x:99,y:99}}})
and return error message that can't use the part(a of a.a1 ) to traverse the elements,so how should I add the element to the array?
Upvotes: 0
Views: 37
Reputation: 1347
mongodb positional/$ The positional $ operator identifies an element in an array to update without explicitly specifying the position of the element in the array. To project, or return, an array element from a read operation, see the $ projection operator.
db.test.update({
_id: ObjectId('...'),
"a.id": 1
}, {
$push: {
"a.$.a1": { x: 99, y: 99 }
}
})
Upvotes: 1