What's the difference between insert(), insertOne(), and insertMany() method?

MongodbNosql

Mongodb Problem Overview


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.

Mongodb Solutions


Solution 1 - Mongodb

>What's the difference between insert(), insertOne() and insertMany() methods on MongoDB

  • 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.

      > var d = db.collection.insert({"b": 3})
      > d
      WriteResult({ "nInserted" : 1 })
      > var d2 = db.collection.insert([{"b": 3}, {'c': 4}])
      > d2
      BulkWriteResult({
              "writeErrors" : [ ],
              "writeConcernErrors" : [ ],
              "nInserted" : 2,
              "nUpserted" : 0,
              "nMatched" : 0,
              "nModified" : 0,
              "nRemoved" : 0,
              "upserted" : [ ]
      })
    
  • db.collection.insertOne() as mentioned in the documentation inserts a document into a collection and returns a document which look like this:

      > var document = db.collection.insertOne({"a": 3})
      > document
      {
              "acknowledged" : true,
              "insertedId" : ObjectId("571a218011a82a1d94c02333")
      }
    
  • db.collection.insertMany() inserts multiple documents into a collection and returns a document that looks like this:

      > var res = db.collection.insertMany([{"b": 3}, {'c': 4}])
      > res
      {
              "acknowledged" : true,
              "insertedIds" : [
                      ObjectId("571a22a911a82a1d94c02337"),
                      ObjectId("571a22a911a82a1d94c02338")
              ]
      }
    

>In what situation should I use each one?

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 to updateOne, updateMany, deleteOne, deleteMany, findOneAndDelete, findOneAndUpdate and findOneAndReplace. See Write Operations Overview.

Solution 2 - Mongodb

  1. db.collection.insert():

    It allows you to insert One or more documents in the collection. Syntax:

  • Single insert: db.collection.insert({<document>});

  • Multiple insert:

      db.collection.insert([
          <document1>, <document2>, ...
      ]);
    

    Returns a WriteResult object: WriteResult({ "nInserted" : 1 });

  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:

    {
       "acknowledged" : true,
       "insertedId" : ObjectId("56fc40f9d735c28df206d078")
    }

3. db.collection.insertMany():

It allows you to insert an array of documents in the collection. Syntax:

    db.collection.insertMany(
        { [ <document 1> , <document 2>, ... ] });

Returns the following document:

    {
       "acknowledged" : true,
       "insertedIds" : [
          ObjectId("562a94d381cb9f1cd6eb0e1a"),
          ObjectId("562a94d381cb9f1cd6eb0e1b"),
          ObjectId("562a94d381cb9f1cd6eb0e1c")
       ]
    }

All three of these also allow you to define a custom writeConcern and also create a collection if it doesn't exist.

Solution 3 - Mongodb

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.

Solution 4 - Mongodb

Also to add to another answer, if the user calls the InsertOne function instead of InsertMany and passes the array of documents to insert. then it is also allowed and will not give any errors. It will create only one document which will have an array of these documents. so be careful.

Solution 5 - Mongodb

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarcos MendesView Question on Stackoverflow
Solution 1 - MongodbstyvaneView Answer on Stackoverflow
Solution 2 - MongodbayushgpView Answer on Stackoverflow
Solution 3 - MongodbAndrew NessinView Answer on Stackoverflow
Solution 4 - Mongodbvivek nunaView Answer on Stackoverflow
Solution 5 - MongodbLeonard Vincent LuzonView Answer on Stackoverflow