1

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]}

nawK
  • 693
  • 1
  • 7
  • 13
  • 1
    `{multi: true}` will update multiple documents but `_id` is unique...if you query on a specific `_id` value you will update at most 1 document. – Paul Mar 30 '19 at 21:23

1 Answers1

1

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.

Paul
  • 19,704
  • 14
  • 78
  • 96
  • Thanks Paul! That makes sense. I should've understood the example more before tinkering with `{multi: true}`. – nawK Mar 30 '19 at 22:32
  • Tinkering is often the best way to understand how example code works. I've learned a lot from breaking example code! – Paul Mar 30 '19 at 22:45