The positional $ operator in MongoDB does not seem to update multiple documents

95 views Asked by At

The following is a modified example from https://docs.mongodb.com/manual/reference/operator/update/positional/#examples

db.students.insert([
   { "_id" : 1, "grades" : [ 85, 80, 80 ] },
   { "_id" : 2, "grades" : [ 88, 90, 92 ] },
   { "_id" : 3, "grades" : [ 85, 100, 90 ] }
])

db.students.updateOne(
   { _id: 1, grades: 80 },
   { $set: { "grades.$" : 82 } }
   { multi: true }
)'

I expect {multi: true} to update multiple documents that match the selector criteria.

As a matter of fact, the following doesn't seem to work either:

db.students.insert([
       { "_id" : 1, "grades" : [ 85, 82, 82 ] },
       { "_id" : 2, "grades" : [ 88, 90, 92 ] },
       { "_id" : 3, "grades" : [ 80, 100, 90 ] }
    ])

    db.students.updateOne(
       { _id: 1, grades: 80 },
       { $set: { "grades.$" : 82 } }
       { multi: true }
    )'

I expect the third document to be updated to {"_id" : 3, "grades" : [82, 100, 90]}

1

There are 1 answers

2
Paul On BEST ANSWER

Your query clause is { _id: 1, grades: 80 } but id:1 has grades : [ 85, 82, 82 ]. The third document will not be updated because it has _id:3 which does not match your query clause.

Pro tip: before running update execute a find to get a preview of what may be updated*.

 db.students.find({ _id: 1, grades: 80 })

*find will return all matches while updateOne will update at most 1 document but at least you'll know your query clause works.