假设post集合中存有如下两条文档:
{
"_id" : ObjectId("4f43bffd0c0b1431f9159164"),
"author" : "Michael",
"comments" : [
{
"user" : "AA",
"vote" : 2
},
{
"user" : "BB",
"vote" : 4
}
],
"title" : "my first post"
}
{
"_id" : ObjectId("4f43bffd0c0b1431f9159164"),
"author" : "Peter",
"comments" : [
{
"user" : "XX",
"vote" : 1
},
{
"user" : "YY",
"vote" : 3
}
],
"title" : "my second post"
}
"_id" : ObjectId("4f43bffd0c0b1431f9159164"),
"author" : "Peter",
"comments" : [
{
"user" : "XX",
"vote" : 1
},
{
"user" : "YY",
"vote" : 3
}
],
"title" : "my second post"
}
现在我想把comments中user为XX的那一条comment的vote数字加1,让它变成2,正确的写法是:
db.post.update({"comments.user":"XX"},{"$inc":{"comments.$.vote":1}});
其中$是定位操作符,使用它的目的是因为在查询出匹配结果之前,我们并不知道这条comment在comments这个数组中的位置(是位置0,还是位置1),因此用$符号占位。同时占位操作法只更新第一个匹配的元素,如果还有一个叫"XX‘的user,那也只有第一个叫“XX”的user vote 值会改变
这里还有一个需要注意的地方是,上面那句命令很容易被写成如下形式:
db.post.update({"author":"Peter"},{"$inc":{"comments.$.vote":1}});
这样写是不对的,你会的到这样一个错误:can't append to array using string field name [$]