Navigation

collection.insertMany()

On this page

Definition

collection.insertMany(documents)

Inserts multiple documents into a collection. The collection.insertMany() method has the following parameter.

Parameter Type Description
documents array An array of documents to insert into the collection.
Returns:A promise that resolves to a JSON object with the following fields:
  • insertedIds: an array of ObjectIDs equal to the _id of each inserted document

Examples

The following examples assume that the test.example namespace has been added to MongoDB in the Stitch admin console and appropriate rules have been set. See MongoDB Rules for more information.

Inserting Multiple Documents

exports = function() {
   const mongodb = context.services.get("mongodb-atlas");
  const collection = mongodb.db("test").collection("example");

   // Create 10 dummy documents
   let docs = [];
   for (let i = 0; i < 10; i++) {
      docs.push({x: i});
   }

   return collection
     .insertMany(docs)
     .then(results => {
       const { insertedIds } = results;
       return insertedIds.map(id => `Found _id: ${id}`)
     });
};

Handling Write Errors

If a write error occurs, the collection.insertMany() promise rejects with an error message. You can handle write errors by appending .catch() statements to your calls to collection.insertMany().

exports = function() {
  const mongodb = context.services.get("mongodb-atlas");
  const collection = mongodb.db("test").collection("example");

  // Create documents with duplicate _id keys
  const docs = [
    { _id: BSON.ObjectId("5a14179d01236a9fc1086df9"), name: "Jack" },
    { _id: BSON.ObjectId("5a14179d01236a9fc1086df9"), name: "Jill" }
  ]
  return collection
    .insertMany(docs); // Insert docs that have duplicate _id keys
    .catch(err => console.error(err.message))
};

The above function returns the following duplicate key error message:

Duplicate key error: E11000 duplicate key error collection: test.example index: _id_ dup key: { : ObjectId('5a14179d01236a9fc1086df9') }