如何在 MongoDB 中进行条件更新?

mongodbdatabasebig data analytics更新于 2026/2/13 3:52:17

在 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" }

相关文章