MongoDB - Insert Documents in a Collection

In MongoDB, a collection represents a table in RDBMS and a document is like a record in a table. Learn how to insert one or more documents into a collection.

MongoDB provides the following methods to insert documents into a collection:

  1. insertOne() - Inserts a single document into a collection.
  2. insert() - Inserts one or more documents into a collection.
  3. insertMany() - Insert multiple documents into a collection.

insert()

The db.<collection>.insert() method inserts one document or an array of documents into a collection.

Syntax:

db.collection.insert(
        document or array of documents, 
        [writeConcern], 
        [ordered])

Parameters:

  1. document or array of documents: A single document or array of documents to insert into the collection.
  2. writeConcern: Optional. A document expressing the write concern to override the default write concern.
  3. ordered: Optional. A boolean value indicating whether it's ordered or unordered insert operation. If true then performs ordered insert where if an error occurs with one of the documents, then MongoDB will return without processing the remaining documents in the array. If false, then process all the documents even if an error occurred. Defaults to true.

The following inserts a single document. It's the same as the insertOne() method.

Example: insert()
db.employees.insert({ 
    firstName: "John",
    lastName: "King",
    email: "[email protected]"
})
Output
{
  acknowledged: true,
  insertedIds: { '0': ObjectId("616d62d9a861820797edd9b2") }
}

The following inserts multiple documents into a collection by passing an array of documents.

Example: Insert a Document
db.employees.insert(
    [
        { 
            firstName: "John",
            lastName: "King",
            email: "[email protected]"
        },
        { 
                firstName: "Sachin",
                lastName: "T",
                email: "[email protected]"
        },
        { 
                firstName: "James",
                lastName: "Bond",
                email: "[email protected]"
        }
    ])
Output
{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId("616d63eda861820797edd9b3"),
    '1': ObjectId("616d63eda861820797edd9b4"),
    '2': ObjectId("616d63eda861820797edd9b5")
  }
}

You can specify a different _id field value into one or more documents, as shown below.

Example: Insert a Document
db.employees.insert(
    [
        { 
            firstName: "John",
            lastName: "King",
            email: "[email protected]"
        },
        { 
                _id:1,
                firstName: "Sachin",
                lastName: "T",
                email: "[email protected]"
        },
        { 
                firstName: "James",
                lastName: "Bond",
                email: "[email protected]"
        },
    ])
Output
{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId("616d63eda861820797edd9b3"),
    '1': 1,
    '2': ObjectId("616d63eda861820797edd9b5")
  }
}

By default, the insert() method performs ordered inserts. So, if an error occurred in any of the documents, then it won't process the remaining documents. For example, the following tries to insert a second document with an existing _id value.

Example: Insert a Document
db.employees.insert(
    [
        { 
            firstName: "Steve",
            lastName: "J",
            email: "[email protected]"
        },
        { 
                _id:1,
                firstName: "Kapil",
                lastName: "D",
                email: "[email protected]"
        },
        { 
                firstName: "Amitabh",
                lastName: "B",
                email: "[email protected]"
        },
    ])
Output
Uncaught:
MongoBulkWriteError: E11000 duplicate key error collection: humanResourceDB.employees index: _id_ dup key: { _id: 1 }
Result: BulkWriteResult {
  result: {
    ok: 1,
    writeErrors: [
      WriteError {
        err: {
          index: 1,
          code: 11000,
          errmsg: 'E11000 duplicate key error collection: humanResourceDB.employees index: _id_ dup key: { _id: 1 }',
          errInfo: undefined,
          op: {
            _id: 1,
            firstName: 'Kapil',
            lastName: 'D',
            email: '[email protected]'
          }
        }
      }
    ],
    writeConcernErrors: [],
    insertedIds: [
      { index: 0, _id: ObjectId("616e6b7e3fa8bd4420d49371") },
      { index: 1, _id: 1 },
      { index: 2, _id: ObjectId("616e6b7e3fa8bd4420d49372") }
    ],
    nInserted: 1,
    nUpserted: 0,
    nMatched: 0,
    nModified: 0,
    nRemoved: 0,
    upserted: []
  }
}

In the above output, it encounters an error while inserting the second document. So, it only inserts the first document. nInserted indicates the number of documents inserted successfully.

Specify the {ordered:false} to perform unorder insert which will insert all the valid documents even if an error occurs.

Example: Insert a Document
db.employees.insert(
    [
        { 
            firstName: "Steve",
            lastName: "J",
            email: "[email protected]"
        },
        { 
                _id:1,
                firstName: "Kapil",
                lastName: "D",
                email: "[email protected]"
        },
        { 
                firstName: "Amitabh",
                lastName: "B",
                email: "[email protected]"
        },
    ],
    { ordered: false}
)
Output
Uncaught:
MongoBulkWriteError: E11000 duplicate key error collection: humanResourceDB.employees index: _id_ dup key: { _id: 1 }
Result: BulkWriteResult {
  result: {
    ok: 1,
    writeErrors: [
      WriteError {
        err: {
          index: 1,
          code: 11000,
          errmsg: 'E11000 duplicate key error collection: humanResourceDB.employees index: _id_ dup key: { _id: 1 }',
          errInfo: undefined,
          op: {
            _id: 1,
            firstName: 'Kapil',
            lastName: 'D',
            email: '[email protected]'
          }
        }
      }
    ],
    writeConcernErrors: [],
    insertedIds: [
      { index: 0, _id: ObjectId("616e6be33fa8bd4420d49373") },
      { index: 1, _id: 1 },
      { index: 2, _id: ObjectId("616e6be33fa8bd4420d49374") }
    ],
    nInserted: 2,
    nUpserted: 0,
    nMatched: 0,
    nModified: 0,
    nRemoved: 0,
    upserted: []
  }
}
ADVERTISEMENT

insertMany()

The db.<collection>.insertMany() inserts multiple documents into a collection. It cannot insert a single document.

Syntax:

db.collection.insertMany(
   [document1, document2, ....],
   {
     writeConcern: <document>,
     ordered: <boolean>
   }
)

The following adds multiple documents using the insertMany() method.

Example: Insert a Document
db.employees.insertMany(
    [
        { 
            firstName: "John",
            lastName: "King",
            email: "[email protected]"
        },
        { 
                firstName: "Sachin",
                lastName: "T",
                email: "[email protected]"
        },
        { 
                firstName: "James",
                lastName: "Bond",
                email: "[email protected]"
        },
    ])
Output
{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId("616d63eda861820797edd9b3"),
    '1': ObjectId("616d63eda861820797edd9b4"),
    '2': ObjectId("616d63eda861820797edd9b5")
  }
}

The following inserts custom _id values.

Example: insertMany() with Custom _id
db.employees.insertMany([
    { 
        _id:1,
        firstName: "John",
        lastName: "King",
        email: "[email protected]",
        salary: 5000
    },
    { 
        _id:2,
        firstName: "Sachin",
        lastName: "T",
        email: "[email protected]",
        salary: 8000
    },
    { 
        _id:3,
        firstName: "James",
        lastName: "Bond",
        email: "[email protected]",
        salary: 7500
    },
    { 
        _id:4,
        firstName: "Steve",
        lastName: "J",
        email: "[email protected]",
        salary: 9000

    },
    { 
        _id:5,
        firstName: "Kapil",
        lastName: "D",
        email: "[email protected]",
        salary: 4500

    },
    { 
        _id:6,
        firstName: "Amitabh",
        lastName: "B",
        email: "[email protected]",
        salary: 11000
    }
])
Output
{
  acknowledged: true,
  insertedIds: { '0': 1, '1': 2, '2': 3, '3': 4, '4': 5, '5': 6 }
}

Use the ordered parameter the same way as the insert() method to process all the documents even if an error occurred.

Note: If the collection used with these methods does not exist, then they create the specified collection. MongoDB is case-sensitive, so employees and Employees are considered two different collections.

Want to check how much you know MongoDB?