测试数据:
{ "_id" : ObjectId("4b97e62bf1d8c7152c9ccb74"), "title" : "ABC", "comments" : [ { "by" : "joe", "votes" : 3 }, { "by" : "jane", "votes" : 7 } ] }
执行更新语句:
语句一:
db.mydb.update({title:"ABC"}, {$inc:{"comments.$.votes":1}}, 0, 1)
执行报错:Cannot apply the positional operator without a corresponding query field containing an array.
语句二:
db.mydb.update({"comments.by":"joe"}, {$inc:{"comments.$.votes":1}}, 0, 1)
执行结果正常
请问是怎么回事?
Comments here is an array (see error message), if you want to update, you need to traverse it
The person above is right, comments is an array, but there is no need to traverse it. The "$" used by the poster is the solution. Just used it wrong. Let’s take a look at what $ means.
In the first two parameters of update, <query conditions> and <update operation>, if the content you query in <query conditions> is the content in the array, you can use the <update operation> Use "$" to reference elements matched in the previous query.
Your second example is querying an array. In the first example, you found
title="ABC"
的doc, 这里匹配查询条件的不包含array. 实际上,你可以把两个例子中的的查询条件写在一起,查询title="..."
and the doc with Joe’s message, and then added the vote of the found Joe’s message by +1.