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 document containing:
  • insertedIds, an array of ObjectIDs equal to the _id of each document inserted

Examples

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

Inserting Multiple Documents

exports = function() {
    var mongodb = context.services.get("mongodb-atlas");
    var coll = mongodb.db("test").collection("example");
    var docs = [];
    for (var i = 0; i < 10; i++) {
        docs.push({x: i});
    }
    coll.insertMany(docs);
};

Handling Write Errors

If a write error occurs, collection.insertMany() throws an exception. This can be handled by wrapping the call to collection.insertMany() in a try/catch block.

exports = function() {
    var mongodb = context.services.get("mongodb-atlas");
    var coll = mongodb.db("test").collection("example");
    try {
        coll.insertMany([{_id: 1}, {_id: 1}]); // inserting with a duplicate key
    } catch (e) {
        // handle write error
        return e.message;
    }
};

The above function returns the duplicate key error message as follows:

"Duplicate key error: E11000 duplicate key error collection: test.example index: _id_ dup key: { : '1' }"