71

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.

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Marcos Mendes
  • 1,091
  • 1
  • 8
  • 15

5 Answers5

107

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.

styvane
  • 59,869
  • 19
  • 150
  • 156
  • Is it deprecated in Node ? – Abdul Rehman Sayed May 30 '16 at 11:20
  • @AbdulRehmanSayed yes in all official drivers even if it's mentioned in the documentation. – styvane May 30 '16 at 11:29
  • Not seeing where `insert()` is deprecated in the [docs](https://docs.mongodb.com/manual/reference/method/db.collection.insert/#db.collection.insert), are you seeing that at some other page? – Brad Solomon Apr 19 '18 at 02:52
  • I think you missed this part: *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* . @BradSolomon – styvane Apr 20 '18 at 17:20
  • Sorry, I didn't @styvane. Thanks for responding – Brad Solomon Apr 20 '18 at 17:22
12
  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([ , , ... ]);

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

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

ayushgp
  • 4,891
  • 8
  • 40
  • 75
  • Hi ayushgp, thanks for you answer. But i'm still in doubt. If insert() solve all situations, why should i use insertOne() or insertMany()? – Marcos Mendes Apr 22 '16 at 11:53
  • 3
    You get the ids of the created documents back with the other 2. Insert just gives you the information about how many documents were created. – ayushgp Apr 22 '16 at 11:54
  • 1
    @MarcosMendes Also [`explain`](https://docs.mongodb.org/manual/reference/method/db.collection.explain/#db.collection.explain) is compatible only with `insert()` and not with insertMany and insertOne. – ayushgp Apr 22 '16 at 11:57
  • Incomplete answer: db.collection.insert() returns BulkWriteResult in case of array of documents as parameter – Dia Sheikh Mar 28 '21 at 09:40
10

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.

Andrew Nessin
  • 1,206
  • 2
  • 15
  • 22
0

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.

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
-2

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.