Navigation

Insert Documents

Overview

The code snippets on this page demonstrate how to insert one or more documents into a MongoDB collection. Insert operations take the documents to add to MongoDB as an argument and return documents that describe the results of the operation.

Note

Data Lake data sources do not support write operations.

Data Model

The examples on this page use a collection named store.items that models various items available for purchase in an online store. Each item has a name, an inventory quantity, and an array of customer reviews.

// store.items
{
    "_id": { "bsonType": "objectId" },
    name: { "bsonType": "string" },
    quantity: { "bsonType": "int" },
    reviews: {
      "bsonType": "array",
      "items": {
        "username": { "bsonType": "string" },
        "comment": { "bsonType": "string" }
      }
    }
}

Snippet Setup

To use a code snippet in a function, you must first instantiate a MongoDB collection handle:

exports = function() {
  const mongodb = context.services.get("mongodb-atlas");
  const itemsCollection = mongodb.db("store").collection("items");
  const purchasesCollection = mongodb.db("store").collection("purchases");
  // ... paste snippet here ...
}

Methods

Insert a Single Document

You can insert a single document using the collection.insertOne() action.

The following function snippet inserts a single item document into the items collection:

const newItem = {
  "name": "Plastic Bricks",
  "quantity": 10,
  "category": "toys",
  "reviews": [{ "username": "legolover", "comment": "These are awesome!" }]
};

itemsCollection.insertOne(newItem)
  .then(result => console.log(`Successfully inserted item with _id: ${result.insertedId}`))
  .catch(err => console.error(`Failed to insert item: ${err}`))

Insert One or More Documents

You can insert multiple documents at the same time using the collection.insertMany() action.

The following function snippet inserts multiple item documents into the items collection:

const doc1 = { "name": "basketball", "category": "sports", "quantity": 20, "reviews": [] };
const doc2 = { "name": "football",   "category": "sports", "quantity": 30, "reviews": [] };

return itemsCollection.insertMany([doc1, doc2])
  .then(result => {
    console.log(`Successfully inserted ${result.insertedIds.length} items!`);
    return result
  })
  .catch(err => console.error(`Failed to insert documents: ${err}`))