Test data:
{ "_id" : ObjectId("4b97e62bf1d8c7152c9ccb74"), "title" : "ABC", "comments" : [ { "by" : "joe", "votes" : 3 }, { "by" : "jane", "votes" : 7 } ] }
Execute update statement:
Statement 1:
db.mydb.update({title:"ABC"}, {$inc:{"comments.$.votes":1}}, 0, 1)
Execute error reporting:Cannot apply the positional operator without a corresponding query field containing an array.
Statement 2:
db.mydb.update({"comments.by":"joe"}, {$inc:{"comments.$.votes":1}}, 0, 1)
The execution result is normal.
What’s going on?
"comments" : [ { "by" : "joe", "votes" : 3 }, { "by" : "jane", "votes" : 7 } ]Comments here is an array (see error message), which needs to be traversed if it is to be updated.