My Input 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 } ] }
]
}
expected update query output
{
_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 } }
]
}
Tried query in these mongoDb manual for $pull but data is not as expected. The output of the below code just delete the entire element not the child element
db.collection.update(
{ },
{ $pull: { results: { $elemMatch: { score: 8 , item: "B" } } } },
{ multi: true }
)
the query you use is removing any item which has score = 'B' and item = '8' from the results array.
the answers array is embedded in the results array, so if you need to remove some elements from the answers array, then you have to add your checks to the answers not the results for example, if you need to remove the answers which have q = 1, and a = 8 then the query should be something like that:
this will update the answers array, not the results array, the result of this query will be