Reputation: 168
I have the following document :
{
"grades" : [
{
"grade" : 80,
"mean" : 75,
"std" : 8,
"otro" : [
{
"i" : 1
},
{
"i" : 2
}
]
},
{
"grade" : 85,
"mean" : 90,
"std" : 5
},
{
"grade" : 85,
"mean" : 90,
"std" : 5,
"otro" : [
{
"i" : 3
},
{
"i" : 4
}
]
},
{
"grade" : 85,
"mean" : 95,
"std" : 6
},
{
"grade" : 90,
"mean" : 85,
"std" : 5,
"otro" : [
{
"i" : 5
},
{
"i" : 6
}
]
}
]
}
What i want to do it's to remove the sub document where 'otro.i' : 2, i have tried this :
db.ejemplo.update(
{
_id: oid,
'grades':
{
$elemMatch:
{
'otro':
{
$elemMatch:
{
'i': 2
}
}
}
}
},
{
'$pull':
{
'grades':
{
'otro':
{
'i':2
}
}
}
}
);
But this removes the all subdocument 'otro' where the key 'i' is equal to 2 ,
this is before :
{
"grade" : 80,
"mean" : 75,
"std" : 8,
"otro" : [
{
"i" : 1
},
{
"i" : 2
}
]
}
this is after
{
"grade" : 80,
"mean" : 75,
"std" : 8
}
But the result i want is :
{
"grade" : 80,
"mean" : 75,
"std" : 8,
"otro" : [
{
"i" : 1
}
]
}
Any ideas ?
Upvotes: 1
Views: 413
Reputation: 103365
Use the $
positional operator to update the document. This identifies an element in an array to update without explicitly specifying the position of the element in the array:
db.ejemplo.update(
{
_id: oid,
'grades':
{
$elemMatch:
{
'otro':
{
$elemMatch:
{
'i': 2
}
}
}
}
},
{
'$pull': {
'grades.$.otro': {"i": 2}
}
}
)
Upvotes: 2