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.

db.collection('inventory').insertOne({
  item: "canvas",
  qty: 100,
  tags: ["cotton"],
  size: { h: 28, w: 35.5, uom: "cm" }
})
.then(function(result) {
  // process result
})

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:

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

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.

db.collection('inventory').insertMany([
  { item: "journal",
    qty: 25,
    tags: ["blank", "red"],
    size: { h: 14, w: 21, uom: "cm" }},
  { item: "mat",
    qty: 85,
    tags: ["gray"],
    size: { h: 27.9, w: 35.5, uom: "cm" }},
  { item: "mousepad",
    qty: 25,
    tags: ["gel", "blue"],
    size: { h: 19, w: 22.85, uom: "cm" }}
])
.then(function(result) {
  // process result
})

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:

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

results matching ""

    No results matching ""