mongodb "$" 操作符问题
天蓬老师
天蓬老师 2017-04-21 11:16:52
0
2
642

测试数据:

{ "_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)

执行结果正常

请问是怎么回事?

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(2)
PHPzhong
 "comments" : [ { "by" : "joe", "votes" : 3 }, { "by" : "jane", 
"votes" : 7 } ]

Comments here is an array (see error message), if you want to update, you need to traverse it

Ty80

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template