只更新 MongoDB 文档中的特定值的方法
要仅更新特定值,请使用update(),然后使用$set设置新值。让我们创建一个包含文档的集合-
> db.demo201.insertOne({"ClientName":"Chris Brown","ClientAge":26}); { "acknowledged" : true, "insertedId" : ObjectId("5e3c39ca03d395bdc21346e5") } > db.demo201.insertOne({"ClientName":"David Miller","ClientAge":35}); { "acknowledged" : true, "insertedId" : ObjectId("5e3c39d403d395bdc21346e6") } > db.demo201.insertOne({"ClientName":"Carol Taylor","ClientAge":28}); { "acknowledged" : true, "insertedId" : ObjectId("5e3c39e603d395bdc21346e7") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo201.find();
这将产生以下输出-
{ "_id" : ObjectId("5e3c39ca03d395bdc21346e5"), "ClientName" : "Chris Brown", "ClientAge" : 26 } { "_id" : ObjectId("5e3c39d403d395bdc21346e6"), "ClientName" : "David Miller", "ClientAge" : 35 } { "_id" : ObjectId("5e3c39e603d395bdc21346e7"), "ClientName" : "Carol Taylor", "ClientAge" : 28 }
以下是更新MongoDB的查询-
> db.demo201.update({"ClientAge":35},{$set:{"ClientName":"John Doe"}},{multi:true}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
在find()方法的帮助下显示集合中的所有文档-
> db.demo201.find();
这将产生以下输出-
{ "_id" : ObjectId("5e3c39ca03d395bdc21346e5"), "ClientName" : "Chris Brown", "ClientAge" : 26 } { "_id" : ObjectId("5e3c39d403d395bdc21346e6"), "ClientName" : "John Doe", "ClientAge" : 35 } { "_id" : ObjectId("5e3c39e603d395bdc21346e7"), "ClientName" : "Carol Taylor", "ClientAge" : 28 }