Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

MongoDB update each element of an embedded array differently

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...