Inserts a document or an array of documents into a collection.
Changed in version 2.2: The insert() method can accept an array of documents to perform a bulk insert of the documents into the collection.
| Parameter | Type | Description |
|---|---|---|
| document | document or array | A document or array of documents to insert into the collection. |
The insert() method has the following behaviors:
The following are examples of the insert() method:
To insert a single document and have MongoDB generate the unique _id, omit the _id field in the document and pass the document to the insert() method as in the following:
db.products.insert( { item: "card", qty: 15 } )
This operation inserts a new document into the products collection with the item field set to card, the qty field set to 15, and the _id field set to a unique ObjectId:
{ "_id" : ObjectId("5063114bd386d8fadbd6b004"), "item" : "card", "qty" : 15 }
Note
Most MongoDB driver clients will include the _id field and generate an ObjectId before sending the insert operation to MongoDB; however, if the client sends a document without an _id field, the mongod will add the _id field and generate the ObjectId.
To insert a single document, with a custom _id field, include the _id field set to a unique identifier and pass the document to the insert() method as follows:
db.products.insert( { _id: 10, item: "box", qty: 20 } )
This operation inserts a new document in the products collection with the _id field set to 10, the item field set to box, the qty field set to 20:
{ "_id" : 10, "item" : "box", "qty" : 20 }
Note
Most MongoDB driver clients will include the _id field and generate an ObjectId before sending the insert operation to MongoDB; however, if the client sends a document without an _id field, the mongod will add the _id field and generate the ObjectId.
To insert multiple documents, pass an array of documents to the insert() method as in the following:
db.products.insert( [ { _id: 11, item: "pencil", qty: 50, type: "no.2" },
{ item: "pen", qty: 20 },
{ item: "eraser", qty: 25 } ] )
The operation will insert three documents into the products collection:
{ "_id" : 11, "item" : "pencil", "qty" : 50, "type" : "no.2" }
{ "_id" : ObjectId("50631bc0be4617f17bb159ca"), "item" : "pen", "qty" : 20 }
{ "_id" : ObjectId("50631bc0be4617f17bb159cb"), "item" : "eraser", "qty" : 25 }