0

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.

1 Answer 1

1

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"
                        ]
                }
        ]
}
Sign up to request clarification or add additional context in comments.

3 Comments

As 'teachers' is an array, there should be something in between, shouldn't there? Like 'teacher.something.teacherName'.
In JS, teachers.forEach(x => if (x.teacherName == 'yyy'){do something}). In this case 'x' is the intermediary, so MongoDB is a different story, isn't it? I did as you said,and it works, but I'm still confused.
there should be something in between, shouldn't there? Like 'teacher.something.teacherName' No, it is not required, in this case.

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.