有条件的更新取决于MongoDB中匹配的字段
对于条件更新,请使用update()
$set并使用其新值。让我们创建一个包含文档的集合-
> db.demo150.insertOne({"StudentId":101,"StudentName":"Chris","StudentMarks":35}); { "acknowledged" : true, "insertedId" : ObjectId("5e350dcdfdf09dd6d08539d3") } > db.demo150.insertOne({"StudentId":102,"StudentName":"Chris","StudentMarks":55}); { "acknowledged" : true, "insertedId" : ObjectId("5e350dcefdf09dd6d08539d4") } > db.demo150.insertOne({"StudentId":103,"StudentName":"David","StudentMarks":34}); { "acknowledged" : true, "insertedId" : ObjectId("5e350dcffdf09dd6d08539d5") } > db.demo150.insertOne({"StudentId":104,"StudentName":"Chris","StudentMarks":38}); { "acknowledged" : true, "insertedId" : ObjectId("5e350dd0fdf09dd6d08539d6") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo150.find();
这将产生以下输出-
{ "_id" : ObjectId("5e350dcdfdf09dd6d08539d3"), "StudentId" : 101, "StudentName" : "Chris", "StudentMarks" : 35 } { "_id" : ObjectId("5e350dcefdf09dd6d08539d4"), "StudentId" : 102, "StudentName" : "Chris", "StudentMarks" : 55 } { "_id" : ObjectId("5e350dcffdf09dd6d08539d5"), "StudentId" : 103, "StudentName" : "David", "StudentMarks" : 34 } { "_id" : ObjectId("5e350dd0fdf09dd6d08539d6"), "StudentId" : 104, "StudentName" : "Chris", "StudentMarks" : 38 }
以下是根据匹配的字段进行条件更新的查询-
> db.demo150.update({"StudentId":103},{$set:{"StudentMarks":97}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
在find()
方法的帮助下显示集合中的所有文档-
> db.demo150.find();
这将产生以下输出-
{ "_id" : ObjectId("5e350dcdfdf09dd6d08539d3"), "StudentId" : 101, "StudentName" : "Chris", "StudentMarks" : 35 } { "_id" : ObjectId("5e350dcefdf09dd6d08539d4"), "StudentId" : 102, "StudentName" : "Chris", "StudentMarks" : 55 } { "_id" : ObjectId("5e350dcffdf09dd6d08539d5"), "StudentId" : 103, "StudentName" : "David", "StudentMarks" : 97 } { "_id" : ObjectId("5e350dd0fdf09dd6d08539d6"), "StudentId" : 104, "StudentName" : "Chris", "StudentMarks" : 38 }