使用学生ID和姓名更新MongoDB文档
要进行更新,请使用UPDATE()和$set。让我们创建一个包含文档的集合-
> db.demo427.insertOne({"StudentId":101,"StudentName":"Chris Brown"}); { "acknowledged" : true, "insertedId" : ObjectId("5e75e711bbc41e36cc3cae75") } > db.demo427.insertOne({"StudentId":102,"StudentName":"David Miller"}); { "acknowledged" : true, "insertedId" : ObjectId("5e75e71abbc41e36cc3cae76") } > db.demo427.insertOne({"StudentId":103,"StudentName":"John Smith"}); { "acknowledged" : true, "insertedId" : ObjectId("5e75e725bbc41e36cc3cae77") } > db.demo427.insertOne({"StudentId":104,"StudentName":"Carol Taylor"}); { "acknowledged" : true, "insertedId" : ObjectId("5e75e733bbc41e36cc3cae78") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo427.find();
这将产生以下输出-
{ "_id" : ObjectId("5e75e711bbc41e36cc3cae75"), "StudentId" : 101, "StudentName" : "Chris Brown" } { "_id" : ObjectId("5e75e71abbc41e36cc3cae76"), "StudentId" : 102, "StudentName" : "David Miller" } { "_id" : ObjectId("5e75e725bbc41e36cc3cae77"), "StudentId" : 103, "StudentName" : "John Smith" } { "_id" : ObjectId("5e75e733bbc41e36cc3cae78"), "StudentId" : 104, "StudentName" : "Carol Taylor" }
以下是更新MongoDB文档的查询-
> db.demo427.update({"StudentId":102},{$set:{"StudentName":"John Doe"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
在find()方法的帮助下显示集合中的所有文档-
> db.demo427.find();
这将产生以下输出-
{ "_id" : ObjectId("5e75e711bbc41e36cc3cae75"), "StudentId" : 101, "StudentName" : "Chris Brown" } { "_id" : ObjectId("5e75e71abbc41e36cc3cae76"), "StudentId" : 102, "StudentName" : "John Doe" } { "_id" : ObjectId("5e75e725bbc41e36cc3cae77"), "StudentId" : 103, "StudentName" : "John Smith" } { "_id" : ObjectId("5e75e733bbc41e36cc3cae78"), "StudentId" : 104, "StudentName" : "Carol Taylor" }