I have a collection of documents (e.g. "students") like this:
{
_id: ObjectId("C24eb7aC0189B18A3D3Ca0FD"),
name: "john doe",
dob: "1993-05-15"
class: "1",
courses: [
{name: "math"},
{name: "geometry"},
{name: "physics"}
]
}
As you can see, each has an embedded array of courses
. Now after the exams, when the grades are determined, I need to update the student document, and add the grade for each course to its object, like so:
{
_id: ObjectId("C24eb7aC0189B18A3D3Ca0FD"),
name: "john doe",
dob: "1993-05-15"
class: "1",
courses: [
{name: "math", grade: 18},
{name: "geometry", grade: 19},
{name: "physics", grade: 16}
]
}
Is there any way that I can do this in a single query? for example I give it an array consisting of the grades and it adds each to the corresponding course
The $[]
operator can perform a constant update on all the elements of the embedded array (e.g. add the same grade for every course) but obviously that's not what I want here.
Also, if it is not possible in a single query, what is the right way to achieve this?
Thanks in advance
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…