日期:2014-05-16 浏览次数:20556 次
? ? 我们前面讲MongoDB的CRUD操作讲过:MongoDB的更新操作通过集合的update()函数实现。这个函数有两个参数:要更改的文档和更改后的样子。要更新文档有两种情况:更新文档和对文档某些部分更新。下面分别说说这两种情况:
??? 1.更新整个文档
??? 假设现在有下面的一个文档:
?
{"name":"zhangsan","dad":"zhangyi","mom":"lisi"};
? ? 如果觉得这样不好,需要讲父亲和母亲的信息组织到一起,成为一个新的文档:parents,另外,加上一个年龄字段age.那么新的文档如下:
?
{"name":"zhangsan","age":20,"parents":{dad:"zhangyi","mom":"lisi"}};
?
??? 如果要将数据库中的第一个文档替代为上面第二个文档,使用update操作的过程如下:
?
> var zhangsan = db.info.findOne({"name" : "zhangsan"}); > zhangsan { "_id" : ObjectId("4ee37409c3fc1a9f80ad74ed"), "name" : "zhangsan", "dad" : "zhangyi", "mom" : "lisi" } > zhangsan.parents={"dad":zhangsan.dad,"mom":zhangsan.mom}; { "dad" : "zhangyi", "mom" : "lisi" } > zhangsan { "_id" : ObjectId("4ee37409c3fc1a9f80ad74ed"), "name" : "zhangsan", "dad" : "zhangyi", "mom" : "lisi", "parents" : { "dad" : "zhangyi", "mom" : "lisi" } } > zhangsan.age=20 20 > zhangsan { "_id" : ObjectId("4ee37409c3fc1a9f80ad74ed"), "name" : "zhangsan", "dad" : "zhangyi", "mom" : "lisi", "parents" : { "dad" : "zhangyi", "mom" : "lisi" }, "age" : 20 } > delete zhangsan.dad true > zhangsan { "_id" : ObjectId("4ee37409c3fc1a9f80ad74ed"), "name" : "zhangsan", "mom" : "lisi", "parents" : { "dad" : "zhangyi", "mom" : "lisi" }, "age" : 20 } > delete zhangsan.mom true > zhangsan { "_id" : ObjectId("4ee37409c3fc1a9f80ad74ed"), "name" : "zhangsan", "parents" : { "dad" : "zhangyi", "mom" : "lisi" }, "age" : 20 } > db.info.update({"_id" : ObjectId("4ee37409c3fc1a9f80ad74ed")},zhangsan); > db.info.find(); { "_id" : ObjectId("4ee37409c3fc1a9f80ad74ed"), "name" : "zhangsan", "parents" : { "dad" : "zhangyi", "mom" : "lisi" }, "age" : 20 } >
?
? ? 以这种方式进行文档更新需要注意一点:尽量通过_id来匹配需要被替换的文档。至于为什么,我想用过数据库的人应该都能明白(类似于用主键去匹配特性的记录)。
??? 2.使用修改器部分修改文档的一部分
??? a) $set修改器
??? $set修改器指定一个键的新值,若不存在则创建新的。我们要给上面的zhangsan文档(数据库中的)添加一个wife键值对。
> db.info.update({"_id" : ObjectId("4ee37409c3fc1a9f80ad74ed")},{"$set":{"wife":"wangwu"}}); > db.info.find(); { "_id" : ObjectId("4ee37409c3fc1a9f80ad74ed"), "age" : 20, "name" : "zhangsan", "parents" : { "dad" : "zhangyi", "mom" : "lisi" }, "wife" : "wangwu" } >
?
?? ? 现在过了一年,张三已经是21岁了,那么可以使用$set更新age键的值:
> db.info.update({"_id" : ObjectId("4ee37409c3fc1a9f80ad74ed")},{"$set":{"age":21}}); > db.info.find(); { "_id" : ObjectId("4ee37409c3fc1a9f80ad74ed"), "age" : 21, "name" : "zhangsan", "parents" : { "dad" : "zhangyi", "mom" : "lisi" }, "wife" : "wangwu" } >
?