1

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

2
  • how it will identify sequence of courses, the array of grades always same as per your courses in collection? can you add request body and input in your question. Commented Jan 8, 2021 at 15:53
  • @turivishal the courses is an array, so it has order. I also have the grades in order. Or if you want I can use an _id for each course. Since I am writing this code, I can make it however I need Commented Jan 8, 2021 at 16:05

1 Answer 1

1

You may try arrayFilters, The filtered positional operator $[<identifier>] identifies the array elements that match the arrayFilters conditions for an update operation, e.g.

db.collection.updateOne({
  "_id": ObjectId("C24eb7aC0189B18A3D3Ca0FD")
},
{
  "$set": {
    "courses.$[e1].grade": 18,
    "courses.$[e2].grade": 19,
    "courses.$[e3].grade": 16
  }
},
{
  "arrayFilters": [
    { "e1.name": "math" },
    { "e2.name": "geometry" },
    { "e3.name": "physics" }
  ]
})

Playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.