手机版
你好,游客 登录 注册
背景:
阅读新闻

MongoDB数据修改总结

[日期:2013-10-25] 来源:Linux社区  作者:huhui_cs [字体:大 中 小]

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 ] }

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款