首页 文章资讯内容详情

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

2026-06-04 1 花语

使用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" }