MongoDB insertOne() inserts a document into a collection, whereas updateOne() update a single document in a collection based on a query filter.
Let us create a collection with documents −
> 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") }
Display all documents from a collection with the help of find() method −
> db.demo735.find();
This will produce the following output −
{ "_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" }
Following is the query to implement updateOne() & insertOne() −
db.demo735.updateOne({id:1},{$set:{Name:"Robert"}}); { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
Display all documents from a collection with the help of find() method −
> db.demo735.find();
This will produce the following output −
{ "_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" }