简体   繁体   中英

How to query an object with a specific key/value pair in an array with Mongodb?

This is my data structure:

{
  studentName: 'zzz',
  teachers: [
    {
      teacherName: 'xxx',
      feedbacks: []
    }, {
      teacherName: 'yyy',
      feedbacks: []
    }
  ]
}

Now I am trying to code a query to add an 'feedback' object to the 'feedbacks' array that belongs to the teacher named 'yyy'.

await collection.updateOne({
                studentName: 'zzz',
                teachers: {
                    $elemMatch: {
                        teacherName: {
                            $eq: 'yyy'
                        }
                    }
                }
            }, {
                $push: {
                    'teachers.$.feedbacks': {}
                }
            })

The query part is faulty somehow. If I change '$' to 0 or 1, then the code works finally. Otherwise, the object cannot be pushed.

This update works fine, adds the string element "Nice work" to the teachers.feedbacks nested array.

db.test.updateOne(
  {
     studentName: "zzz",
     "teachers.teacherName": "yyy"
   },
   { $push: { "teachers.$.feedbacks" : "Nice work" } }
)

The $elemMatch syntax is not required, as the query condition for the array elements is for a single field.

The updated document:

{
        "studentName" : "zzz",
        "teachers" : [
                {
                        "teacherName" : "xxx",
                        "feedbacks" : [ ]
                },
                {
                        "teacherName" : "yyy",
                        "feedbacks" : [
                                "Nice work"
                        ]
                }
        ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM