Reputation: 31
Find by Sub Document by multiple Id and update its data. Below example says that find the data by grades.id and update its corresponding mean value to 100.
MongoDB Version : 3.4 and 3.6
Update subdocument by subdocument Id - Array of Subdocument ID
Schema:
{
"_id" : 1,
"grades" : [
{
"id" : 1,
"grade" : 80,
"mean" : 75,
"std" : 6
},
{
"id" : 2,
"grade" : 85,
"mean" : 90,
"std" : 4
},
{
"id" : 3,
"grade" : 85,
"mean" : 85,
"std" : 6
}
]
}
Query:
db.students.update(
{_id: 1},
{ $set: { "grades.$[elem].mean" : 100 } },
{
multi: true,
arrayFilters: [ { "elem._id": { $in: [1, 2] } } ]
}
)
OutPut
{
"_id" : 1,
"grades" : [
{
"id" : 1,
"grade" : 100,
"mean" : 75,
"std" : 6
},
{
"id" : 2,
"grade" : 100,
"mean" : 90,
"std" : 4
},
{
"id" : 3,
"grade" : 85,
"mean" : 85,
"std" : 6
}
]
}
I have tried above query but its fail
Error cannot use the part (grades of grades.$[elem].mean) to traverse the element
Upvotes: 0
Views: 312
Reputation: 10918
Running this query against v3.4 cannot work since it simply doesn't support this new array filtering functionality. So you have to run your query against v3.6.
And then you've probably got the following two problems here:
Your arrayFilters: [ { "elem._id": { $in: [1, 2] } } ]
should reference the correct field name which is "elem.id"
only (without the underscore).
You are probably using Robomongo (or similar) as a client to run your query. I don't exactly know what's happening here but that simply doesn't work. Once you use the Mongo shell everything works as expected.
Upvotes: 1