如何对 MongoDB 中的条件进行更新?
在 MongoDB 中使用 update() 执行条件更新。我们先使用文档创建一个集合 −
> 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" }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP