MongoDB入门3——更新文档和修改器1
我们前面讲MongoDB的CRUD操作讲过:MongoDB的更新操作通过集合的update()函数实现。这个函数有两个参数:要更改的文档和更改后的样子。要更新文档有两种情况:更新文档和对文档某些部分更新。下面分别说说这两种情况:1.更新整个文档
假设现在有下面的一个文档:
{"name":"zhangsan","dad":"zhangyi","mom":"lisi"};
{"name":"zhangsan","dad":"zhangyi","mom":"lisi"}; 如果觉得这样不好,需要讲父亲和母亲的信息组织到一起,成为一个新的文档:parents,另外,加上一个年龄字段age.那么新的文档如下:
{"name":"zhangsan","age":20,"parents":{dad:"zhangyi","mom":"lisi"}};
{"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 }
>
> 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",
&