MongoDB insertOne()将文档插入到集合中,而updateOne()基于查询过滤器更新集合中的单个文档。
让我们创建一个包含文档的集合-
> db.demo735.insertOne({id:1,Name:"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5ead51b657bb72a10bcf0652") } > db.demo735.insertOne({id:1,Name:"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5ead51bb57bb72a10bcf0653") } > db.demo735.insertOne({id:1,Name:"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5ead51be57bb72a10bcf0654") } > db.demo735.insertOne({id:1,Name:"Carol"}); { "acknowledged" : true, "insertedId" : ObjectId("5ead51c757bb72a10bcf0655") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo735.find();
这将产生以下输出-
{ "_id" : ObjectId("5ead51b657bb72a10bcf0652"), "id" : 1, "Name" : "Chris" } { "_id" : ObjectId("5ead51bb57bb72a10bcf0653"), "id" : 1, "Name" : "David" } { "_id" : ObjectId("5ead51be57bb72a10bcf0654"), "id" : 1, "Name" : "Bob" } { "_id" : ObjectId("5ead51c757bb72a10bcf0655"), "id" : 1, "Name" : "Carol" }
以下是实现updateOne()和insertOne()的查询-
db.demo735.updateOne({id:1},{$set:{Name:"Robert"}}); { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
在find()方法的帮助下显示集合中的所有文档-
> db.demo735.find();
这将产生以下输出-
{ "_id" : ObjectId("5ead51b657bb72a10bcf0652"), "id" : 1, "Name" : "Robert" } { "_id" : ObjectId("5ead51bb57bb72a10bcf0653"), "id" : 1, "Name" : "David" } { "_id" : ObjectId("5ead51be57bb72a10bcf0654"), "id" : 1, "Name" : "Bob" } { "_id" : ObjectId("5ead51c757bb72a10bcf0655"), "id" : 1, "Name" : "Carol" }