12). $
可以理解为数组定位器,看一个官方文档的例子:
> t.find()
{ "_id" : ObjectId("4b97e62bf1d8c7152c9ccb74"), "title" : "ABC", "comments" : [ { "by" : "joe", "votes" : 3 }, { "by" : "jane", "votes" : 7 } ] }
> t.update( {'comments.by':'joe'}, {$inc:{'comments.$.votes':1}})
> t.find()
{ "_id" : ObjectId("4b97e62bf1d8c7152c9ccb74"), "title" : "ABC", "comments" : [ { "by" : "joe", "votes" : 4 }, { "by" : "jane", "votes" : 7 } ] }
需要注意的是,$只会找到第一条数组项,后面的就不管了:
> db.mytest.find({_id:16})
{ "_id" : 16, "x" : [ 1, 2, 3, 1 ] }
> db.mytest.update({x:1},{$inc:{"x.$":1}})
> db.mytest.find({_id:16})
{ "_id" : 16, "x" : [ 2, 2, 3, 1 ] }
还有一点需要注意,当$配合$unset使用的时候,会留下一个null的数组项,这个问题可以使用{$pull:{x:null}}解决:
> db.mytest.find({_id:16})
{ "_id" : 16, "x" : [ 2, 2, 3, 1 ] }
> db.mytest.update({x:3},{$unset:{"x.$":1}})
> db.mytest.find({_id:16})
{ "_id" : 16, "x" : [ 2, 2, null, 1 ] }
> db.mytest.update({_id:16},{$pull:{x:null}})
> db.mytest.find({_id:16})
{ "_id" : 16, "x" : [ 2, 2, 1 ] }
