Navigation

collection.insertOne()

On this page

Definition

collection.insertOne(document)

Inserts a document into a collection. The collection.insertOne() method has the following parameter.

Parameter Type Description
document document A document to insert into the collection.
Returns:A document containing:
  • insertedId equal to the the _id of the inserted document

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 a Document

exports = function() {
    var mongodb = context.services.get("mongodb-atlas");
    var coll = mongodb.db("test").collection("example");
    coll.insertOne({x: 1});
};

Handling Write Errors

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

exports = function() {
    var mongodb = context.services.get("mongodb-atlas");
    var coll = mongodb.db("test").collection("example");
    try {
        coll.insertOne({_id: 1});
        coll.insertOne({_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' }"