如何在MongoDB中进行条件更新?
使用update()在MongoDB中进行条件更新。首先让我们创建一个包含文档的集合-
> db.demo402.insertOne({id:101,"Name":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e61214efac4d418a0178585")
}
> db.demo402.insertOne({id:102,"Name":"David"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e612150fac4d418a0178586")
}
> db.demo402.insertOne({id:103,"Name":"Mike"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e612152fac4d418a0178587")
}在find()方法的帮助下显示集合中的所有文档-
> db.demo402.find();
这将产生以下输出-
{ "_id" : ObjectId("5e61214efac4d418a0178585"), "id" : 101, "Name" : "Chris" }
{ "_id" : ObjectId("5e612150fac4d418a0178586"), "id" : 102, "Name" : "David" }
{ "_id" : ObjectId("5e612152fac4d418a0178587"), "id" : 103, "Name" : "Mike" }以下是在MongoDB中执行条件更新的查询-
> db.demo402.update({id:102},
... {
... $set: { Name: "Robert" }
... },
... {upsert: true }
... )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })在find()方法的帮助下显示集合中的所有文档-
> db.demo402.find();
这将产生以下输出-
{ "_id" : ObjectId("5e61214efac4d418a0178585"), "id" : 101, "Name" : "Chris" }
{ "_id" : ObjectId("5e612150fac4d418a0178586"), "id" : 102, "Name" : "Robert" }
{ "_id" : ObjectId("5e612152fac4d418a0178587"), "id" : 103, "Name" : "Mike" }热门推荐
10 祝孙辈生日祝福语简短
11 恋人跨年祝福语大全简短
12 考大学敬酒简短祝福语
13 开工投产大吉祝福语 简短
14 偶然结婚祝福语朋友简短
15 感谢学长学姐祝福语简短
16 戏精的祝福语简短
17 我要结婚祝福语简短
18 婚前女儿生日祝福语简短