MongoDB--使用修改器修改文档

时间:2020-12-29 20:02:49

可以使用修改器啦修改文档,比如增加、删除文档的键值。使用修改器首先要定位到某个文档, 然后再增加相应的修改选项,需要使用update语句

1.$inc修改器修改文档

> db.users.findOne({'name':'cd'});
{
"_id" : ObjectId("584eafa97629396db95535da"),
"name" : "cd",
"sex" : "M",
"information" : {
"age" : 23,
"address" : "Shanghai"
}
}
> db.users.update({"name": "cd"},
... {"$inc":{"qq": 123456789}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.users.findOne({'name':'cd'});
{
"_id" : ObjectId("584eafa97629396db95535da"),
"name" : "cd",
"sex" : "M",
"information" : {
"age" : 23,
"address" : "Shanghai"
},
"qq" : 123456789
}
>

命令解释:

db.users.findOne() -->查询某个文档,可以添加具体的参数,只返回一个文档,如上例子查询文档键name的值为cd的该文档

db.users.update() -->更新某个文档,一般带有两个参数,一个参数定位到更新那个文档,另一个参数设置修改内容

{"$inc":{"key" : "value"}}-->修改键key对应的值,若key不存在,则创建key

流程:

1.首先查询name为cd的文档,看文档里面的具体键值

2.使用修改器$inc和更新语句更新集合中的文档

3.再次查询name为cd的文档,和步骤1的查询结果对比,看更新文档是否成功

2.$set修改器修改文档

> db.users.findOne({"name":"scd"});
{
"_id" : ObjectId("58549695a14618fbeef3bf0f"),
"name" : "scd",
"sex" : "M",
"address" : "上海"
}
> db.users.update( {"name":"scd"},
... {"$set":{"lang": ["中文", "english"]}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.users.findOne({"name":"scd"});
{
"_id" : ObjectId("58549695a14618fbeef3bf0f"),
"name" : "scd",
"sex" : "M",
"address" : "上海",
"lang" : [
"中文",
"english"
]
}
>

3.$unset修改器,删除文档中的某个键

> db.users.findOne({"name":"scd"});
{
"_id" : ObjectId("58549885a14618fbeef3bf11"),
"name" : "scd",
"sex" : "M",
"address" : "上海",
"lang" : [
"中文",
"english"
]
}
> db.users.update({"name":"scd"},
... {"$unset":{"sex":"M"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.users.findOne({"name":"scd"});
{
"_id" : ObjectId("58549885a14618fbeef3bf11"),
"name" : "scd",
"address" : "上海",
"lang" : [
"中文",
"english"
]
}
>

操作结果:删除键name值为scd文档的键sex

4.$set和$inc修改器的区别

$inc只能由于修改整型、长整型或双精度浮点型的值

> db.users.findOne({"name":"scd"});
{
"_id" : ObjectId("58549885a14618fbeef3bf11"),
"name" : "scd",
"address" : "上海",
"lang" : [
"中文",
"english"
]
}
> db.users.update({"name":"scd"},
... {"$inc":{"address": "北京"}});
WriteResult({
"nMatched" : 0,
"nUpserted" : 0,
"nModified" : 0,
"writeError" : {
"code" : 14,
"errmsg" : "Cannot increment with non-numeric argument: {address: \"鍖椾含\"}"
}
})

使用$inc修改键对应的数值为字符串会报错 "writeError"

而使用$set可以修改键对应的值为字符类型的数值

> db.users.findOne({"name":"scd"});
{
"_id" : ObjectId("58549885a14618fbeef3bf11"),
"name" : "scd",
"address" : "上海",
"lang" : [
"中文",
"english"
]
}
> db.users.update({"name":"scd"},
... {"$set":{"address":"北京"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.users.findOne("name":"scd");
2016-12-17T09:55:20.213+0800 E QUERY [thread1] SyntaxError: missing ) after argument list @(shell):1:23 > db.users.findOne({"name":"scd"});
{
"_id" : ObjectId("58549885a14618fbeef3bf11"),
"name" : "scd",
"address" : "北京",
"lang" : [
"中文",
"english"
]
}
>

$set修改器可以修改许多类型的数值,如字符串、数组等等