mongo-embedded心得

大家都知道,mongo支持对embbeded的子项进行查询和更新操作,其实mongo从1.3.4之后支持对数组中的item为对象的进行查询和更新操作。


'$'符号是进行这类查询的基础。首先,我们要理解他的含义。
官方文档中说到:“The $ operator (by itself) means "position of the matched array item in the query".”该符号指的就是在制定的数组中匹配的item的位置,因此我们看到了希望。下面是它的例子:

> 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}}, false, true ) 
、**这句是指根据{'comments.by':'joe'}找到匹配的项,然后根据该项所在的位置将投票数增加1
> t.find()
{ "_id" : ObjectId("4b97e62bf1d8c7152c9ccb74"), "title" : "ABC",
  "comments" : [ { "by" : "joe", "votes" : 4 }, { "by" : "jane", "votes" : 7 } ] }

 “Currently the $ operator only applies to the first matched item in the query”,从这句话可知,它只会更新匹配到的第一个元素,而不是所有的元素。

> t.find();
{ "_id" : ObjectId("4b9e4a1fc583fa1c76198319"), "x" : [ 1, 2, 3, 2 ] }
> t.update({x: 2}, {$inc: {"x.$": 1}}, false, true);
> t.find();
{ "_id" : ObjectId("4b9e4a1fc583fa1c76198319"), "x" : [ 1, 3, 3, 2 ] }
//显然只是将第一个2增加了1
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值