MongoDB入门4――更新文档和修改器2 (三)

2014-11-24 07:50:48 ? 作者: ? 浏览: 12
om" }
>

> db.users.update({"_id" : ObjectId("4ee49adeaf9c9fecc9c9cf62")},{"$set":{"emailaddrs.0":"bbb@b.com"}});
> db.users.find();
{ "_id" : ObjectId("4ee49adeaf9c9fecc9c9cf62"), "emailaddrs" : [ "bbb@b.com", "d@b.com" ], "name" : "Tom" }
> 上面的情况有个不足:不查询出结果怎么知道顺序呢。为了解决这个问题,引入了$定位操作符。用来匹配查询条件查询出来的结果(也就是update的第一个参数)。

回到上面那个评论的例子,我们要修改把评论人为xiaobai的评论的评论人改成xiaoxiaobai。


> db.blog.update({"comments.name":"xiaobai"},{"$set":{"comments.$.name":"xiaoxiaobai"}});
> db.blog.find()
{ "_id" : ObjectId("4ee47369af9c9fecc9c9cf61"), "comments" : [ { "content" : "very good", "name" : "xiaoxiaobai" }, { "name" : "xiaohong", "content" : "very very good" }, { "name" : "lisi", "comment" : "Not Bad" } ], "content" : "MongoDB tutorial...", "title" : "A New Blog" }
>

> db.blog.update({"comments.name":"xiaobai"},{"$set":{"comments.$.name":"xiaoxiaobai"}});
> db.blog.find()
{ "_id" : ObjectId("4ee47369af9c9fecc9c9cf61"), "comments" : [ { "content" : "very good", "name" : "xiaoxiaobai" }, { "name" : "xiaohong", "content" : "very very good" }, { "name" : "lisi", "comment" : "Not Bad" } ], "content" : "MongoDB tutorial...", "title" : "A New Blog" }
> 如果有多条匹配,则只会修改第一条。

上面就是基本的修改器了。

参考书籍:

《MongoDB:The definitive guide》


摘自 wawlian说
-->

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: