Navigation

collection.insertOne()

Definition

collection.insertOne()

Insert a single document into a collection and return the _id of the inserted document.

Usage

Example

To call the collection.insertOne() action from a Function, get a collection handle with database.collection() then call the handle’s insertOne() method.

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}`))

To call the collection.insertOne() action from a JavaScript SDK, use the RemoteMongoCollection.insertOne() method.

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}`))

To call the collection.insertOne() action from the Java/Android SDK, use the RemoteMongoCollection.insertOne() method.

Document newItem = new Document()
    .append("name", "legos")
    .append("quantity", 10)
    .append("category", "toys")
    .append("reviews", Arrays.asList(
        new Document()
        .append("username", "mongolover")
        .append("comment", "this is great")
    ));


final Task <RemoteInsertOneResult> insertTask = itemsCollection.insertOne(newItem);
insertTask.addOnCompleteListener(new OnCompleteListener <RemoteInsertOneResult> () {
    @Override
    public void onComplete(@NonNull Task <RemoteInsertOneResult> task) {
        if (task.isSuccessful()) {
            Log.d("app", String.format("successfully inserted item with id %s",
                task.getResult().getInsertedId()));
        } else {
            Log.e("app", "failed to insert document with: ", task.getException());
        }
    }
});

To call the collection.insertOne() action from the Swift/iOS SDK, use the RemoteMongoCollection.insertOne() method.

let newItem: Document = [
    "name": "Plastic Bricks",
    "quantity": 10,
    "category": "toys",
    "reviews": [
        [
            "username": "legolover",
            "comment": "These are awesome!"
        ] as Document
    ],
];

itemsCollection?.insertOne(newItem) { result in
    switch result {
    case .success(let result):
        print("Successfully inserted item with _id: \(result.insertedId))");
    case .failure(let error):
        print("Failed to insert item: \(error)");
    }
}

Parameters

The collection.insertOne() action has the following form:

insertOne(document)
Parameter Description

Insert Document

document: <document>
A document to insert into the collection.

The insertOne() method has the following form:

insertOne(document)
Parameter Description

Insert Document

document: <document>
A document to insert into the collection.

The insertOne() method has the following form:

insertOne(document)
Parameter Description

Insert Document

document: <document>
A document to insert into the collection.

The insertOne() method has the following form:

insertOne(document)
Parameter Description

Insert Document

document: <document>
A document to insert into the collection.

Return Value

The collection.insertOne() action returns a Promise that resolves to a document that describes the insert operation.

Promise<result: document>

The RemoteMongoCollection.insertOne() method returns a Promise that resolves to a RemoteInsertOneResult object that describes the insert operation.

Promise<result: RemoteInsertOneResult>

The RemoteMongoCollection.insertOne() method returns a Task that resolves to a RemoteInsertOneResult object that describes the insert operation.

Task<RemoteInsertOneResult result>

The RemoteMongoCollection.insertOne() method returns a StitchResult enum that resolves to a RemoteInsertOneResult object that describes the insert operation.

enum StitchResult {
  case success(result: RemoteInsertOneResult)
  case failure(error: StitchError)
}
Value Description

Inserted ID

result.insertedId: <ObjectID>
result.insertedId: <ObjectID>
result.insertedId: <ObjectID>
result.insertedId: <ObjectID>
The _id value of the document that the insert operation added to the collection.

Examples

The following examples assume that you have defined roles and permissions that allow the database operations on the test.example collection.

Inserting a Document

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

  return collection
    .insertOne({x: 1})
    .then(result => {
      const { insertedId } = result;
      // Do something with the insertedId
      return `Inserted document with _id: ${insertedId}`;
   });
};

Handling Write Errors

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

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

  const tryInsert = doc => {
    return collection
      .insertOne(doc)
      .catch(err => console.error(err.message));
  }

  return tryInsert({ name: "Rick" }).then( ({ insertedId }) => {
    // Insert another document with a duplicate key
    // This promise will reject
    tryInsert({ _id: insertedId, name: "Morty" });
  })
};

The second tryInsert promise rejects with the following duplicate key error message:

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