Insert Documents

This page provides examples of insert operations in MongoDB.

CREATING A COLLECTION

If the collection does not currently exist, insert operations will create the collection.

Insert a Single Document

New in version 3.2.

Collection.insertOne()inserts asingledocumentinto a collection.

The following example inserts a new document into theinventorycollection. If the document does not specify an_idfield, the Node.js driver adds the_idfield with an ObjectId value to the new document. SeeInsert Behavior.

  1. db.collection('inventory').insertOne({
  2. item: "canvas",
  3. qty: 100,
  4. tags: ["cotton"],
  5. size: { h: 28, w: 35.5, uom: "cm" }
  6. })
  7. .then(function(result) {
  8. // process result
  9. })

insertOne()returns a promise that provides aresult. Theresult.insertedIdpromise contains the_idof the newly inserted document.

To retrieve the document that you just inserted,query the collection:

  1. var cursor = db.collection('inventory').find({
  2. item: "canvas",
  3. });

Insert Multiple Documents

New in version 3.2.

Collection.insertMany()can insertmultipledocumentsinto a collection. Pass an array of documents to the method.

The following example inserts three new documents into theinventorycollection. If the documents do not specify an_idfield, the Node.js driver adds the_idfield with an ObjectId value to each document. SeeInsert Behavior.

  1. db.collection('inventory').insertMany([
  2. { item: "journal",
  3. qty: 25,
  4. tags: ["blank", "red"],
  5. size: { h: 14, w: 21, uom: "cm" }},
  6. { item: "mat",
  7. qty: 85,
  8. tags: ["gray"],
  9. size: { h: 27.9, w: 35.5, uom: "cm" }},
  10. { item: "mousepad",
  11. qty: 25,
  12. tags: ["gel", "blue"],
  13. size: { h: 19, w: 22.85, uom: "cm" }}
  14. ])
  15. .then(function(result) {
  16. // process result
  17. })

insertMany()returns a promise that provides aresult. Theresult.insertedIdsfield contains an array with the_idof each newly inserted document.

To retrieve the inserted documents,query the collection:

  1. var cursor = db.collection('inventory').find({});

Insert Behavior

Collection Creation

If the collection does not currently exist, insert operations will create the collection.

_idField

In MongoDB, each document stored in a collection requires a unique_idfield that acts as aprimary key. If an inserted document omits the_idfield, the MongoDB driver automatically generates anObjectIdfor the_idfield.

This also applies to documents inserted through update operations withupsert: true.

Atomicity

All write operations in MongoDB are atomic on the level of a single document. For more information on MongoDB and atomicity, seeAtomicity and Transactions

Write Acknowledgement

With write concerns, you can specify the level of acknowledgement requested from MongoDB for write operations. For details, seeWrite Concern.

SEE ALSO