Hi,
In $pull documentation we find an exemple to pull an element from an array.
See https://docs.mongodb.com/manual/reference/operator/update/pull/
Source data :
{
_id: 1,
results: [
{ item: "A", score: 5, answers: [ { q: 1, a: 4 }, { q: 2, a: 6 } ] },
{ item: "B", score: 8, answers: [ { q: 1, a: 8 }, { q: 2, a: 9 } ] }
]
}
{
_id: 2,
results: [
{ item: "C", score: 8, answers: [ { q: 1, a: 8 }, { q: 2, a: 7 } ] },
{ item: "B", score: 4, answers: [ { q: 1, a: 0 }, { q: 2, a: 8 } ] }
]
}
The query :
db.survey.update(
{ },
{ $pull: { results: { answers: { $elemMatch: { q: 2, a: { $gte: 8 } } } } } },
{ multi: true }
)
This end with this result :
{
"_id" : 1,
"results" : [
{ "item" : "A", "score" : 5, "answers" : [ { "q" : 1, "a" : 4 }, { "q" : 2, "a" : 6 } ] }
]
}
{
"_id" : 2,
"results" : [
{ "item" : "C", "score" : 8, "answers" : [ { "q" : 1, "a" : 8 }, { "q" : 2, "a" : 7 } ] }
]
}
The query removed the entier result
(probably as expected ).
I am looking for a way to only remove the anwser
that match and not the entirer result.
Expected result :
{
_id: 1,
results: [
{ item: "A", score: 5, answers: [ { q: 1, a: 4 }, { q: 2, a: 6 } ] },
{ item: "B", score: 8, answers: [ { q: 1, a: 8 } ] }
]
}
{
_id: 2,
results: [
{ item: "C", score: 8, answers: [ { q: 1, a: 8 }, { q: 2, a: 7 } ] },
{ item: "B", score: 4, answers: [ { q: 1, a: 0 } ] }
]
}
I tried things around $ and $ but not luck.
When I will figure out this then I will want to filter results too before looking into anwsers. For exemple only if restults.score
is $get
to 8 so final result should be :
{
_id: 1,
results: [
{ item: "A", score: 5, answers: [ { q: 1, a: 4 }, { q: 2, a: 6 } ] },
{ item: "B", score: 8, answers: [ { q: 1, a: 8 } ] }
]
}
{
_id: 2,
results: [
{ item: "C", score: 8, answers: [ { q: 1, a: 8 }, { q: 2, a: 7 } ] },
{ item: "B", score: 4, answers: [ { q: 1, a: 0 }, { q: 2, a: 8 } ] }
]
}