MongoDB - Insert Multiple 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:
- insertOne() - Inserts a single document into a collection.
- insert() - Inserts one or more documents into a collection.
- 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:
- document or array of documents: A single document or array of documents to insert into the collection.
- writeConcern: Optional. A document expressing the write concern to override the default write concern.
- 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. Iffalse
, then process all the documents even if an error occurred. Defaults totrue
.
The following inserts a single document. It's the same as the insertOne()
method.
db.employees.insert({
firstName: "John",
lastName: "King",
email: "[email protected]"
})
{
acknowledged: true,
insertedIds: { '0': ObjectId("616d62d9a861820797edd9b2") }
}
The following inserts multiple documents into a collection by passing an array of documents.
db.employees.insert(
[
{
firstName: "John",
lastName: "King",
email: "[email protected]"
},
{
firstName: "Sachin",
lastName: "T",
email: "[email protected]"
},
{
firstName: "James",
lastName: "Bond",
email: "[email protected]"
}
])
{
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.
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]"
},
])
{
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.
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]"
},
])
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.
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}
)
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: []
}
}
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.
db.employees.insertMany(
[
{
firstName: "John",
lastName: "King",
email: "[email protected]"
},
{
firstName: "Sachin",
lastName: "T",
email: "[email protected]"
},
{
firstName: "James",
lastName: "Bond",
email: "[email protected]"
},
])
{
acknowledged: true,
insertedIds: {
'0': ObjectId("616d63eda861820797edd9b3"),
'1': ObjectId("616d63eda861820797edd9b4"),
'2': ObjectId("616d63eda861820797edd9b5")
}
}
The following inserts custom _id
values.
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
}
])
{
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.