将findOneAndUpdate()
用于更新仅在MongoDB中一个文件。让我们创建一个包含文档的集合-
db.demo349.insertOne({"Name":"Chris","Marks":56}); { "acknowledged" : true, "insertedId" : ObjectId("5e55384af8647eb59e5620b4") } > db.demo349.insertOne({"Name":"David","Marks":78}); { "acknowledged" : true, "insertedId" : ObjectId("5e553853f8647eb59e5620b5") } > db.demo349.insertOne({"Name":"Chris","Marks":89}); { "acknowledged" : true, "insertedId" : ObjectId("5e55385af8647eb59e5620b6") } > db.demo349.insertOne({"Name":"David","Marks":54}); { "acknowledged" : true, "insertedId" : ObjectId("5e55385ff8647eb59e5620b7") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo349.find();
这将产生以下输出-
{ "_id" : ObjectId("5e55384af8647eb59e5620b4"), "Name" : "Chris", "Marks" : 56 } { "_id" : ObjectId("5e553853f8647eb59e5620b5"), "Name" : "David", "Marks" : 78 } { "_id" : ObjectId("5e55385af8647eb59e5620b6"), "Name" : "Chris", "Marks" : 89 } { "_id" : ObjectId("5e55385ff8647eb59e5620b7"), "Name" : "David", "Marks" : 54 }
以下是与MongoDB中的findOneAndUpdate配合使用的查询-
> db.demo349.findOneAndUpdate({ "Name" : "David" },{$inc:{Marks:10}}); { "_id" : ObjectId("5e553853f8647eb59e5620b5"), "Name" : "David", "Marks" : 78 }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo349.find();
这将产生以下输出-
{ "_id" : ObjectId("5e55384af8647eb59e5620b4"), "Name" : "Chris", "Marks" : 56 } { "_id" : ObjectId("5e553853f8647eb59e5620b5"), "Name" : "David", "Marks" : 88 } { "_id" : ObjectId("5e55385af8647eb59e5620b6"), "Name" : "Chris", "Marks" : 89 } { "_id" : ObjectId("5e55385ff8647eb59e5620b7"), "Name" : "David", "Marks" : 54 }