What's the difference between insert()
, insertOne()
and insertMany()
methods on MongoDB. In what situation should i use each one?
I read the docs, but it's not clear when use each one.
What's the difference between insert()
, insertOne()
and insertMany()
methods on MongoDB. In what situation should i use each one?
I read the docs, but it's not clear when use each one.
db.collection.insert()
as mentioned in the documentation inserts a document or documents into a collection and returns a WriteResult object for single inserts and a BulkWriteResult object for bulk inserts.db.collection.insertOne()
as mentioned in the documentation inserts a document into a collection and returns a document which look like this:db.collection.insertMany()
inserts multiple documents into a collection and returns a document that looks like this:The
insert()
method is deprecated in major driver so you should use the the.insertOne()
method whenever you want to insert a single document into your collection and the.insertMany
when you want to insert multiple documents into your collection. Of course this is not mentioned in the documentation but the fact is that nobody really writes an application in the shell. The same thing applies toupdateOne
,updateMany
,deleteOne
,deleteMany
,findOneAndDelete
,findOneAndUpdate
andfindOneAndReplace
. See Write Operations Overview.db.collection.insert()
:It allows you to insert One or more documents in the collection. Syntax:
db.collection.insert({<document>});
Multiple insert:
db.collection.insert([ , , ... ]);
Returns a
WriteResult
object:WriteResult({ "nInserted" : 1 });
db.collection.insertOne()
:It allows you to insert exactly 1 document in the collection. Its syntax is the same as that of single insert in
insert()
.Returns the following document:
db.collection.insertMany()
:It allows you to insert an array of documents in the collection. Syntax:
Returns the following document:
All three of these also allow you to define a custom
writeConcern
and also create a collection if it doesn't exist.If the collection does not exist, then the insertOne() method creates the collection. If you input the same data again, mongod will create another unique id to avoid duplication.
There is also a difference in error handling, check here. The insert command returns a document in both success and error cases. But the insertOne and insertMany commands throws exceptions. Exceptions are easier to handle in code, than evaluating the returned document to figure out errors. Probably the reason why they are deprecated in the drivers as mentioned in sstyvane's answer.