Navigation

Update Documents

Overview

The code snippets on this page demonstrate how to update documents that are stored in a MongoDB collection. Update operations use query filters to specify which documents to update and update operators to describe the changes to apply to matching documents.

This page also covers several different update operators that you can use to update fields or update array values.

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

Update a Single Document

You can update a single document using the collection.updateOne() action.

The following function snippet updates the name of a single document in the items collection from legos to blocks and adds a price of 20.99:

const query = { "name": "legos" };
const update = {
  "$set": {
    "name": "blocks",
    "price": 20.99,
    "category": "toys"
  }
};
const options = { "upsert": false };

itemsCollection.updateOne(query, update, options)
  .then(result => {
    const { matchedCount, modifiedCount } = result;
    if(matchedCount && modifiedCount) {
      console.log(`Successfully updated the item.`)
    }
  })
  .catch(err => console.error(`Failed to update the item: ${err}`))

Update One or More Documents

You can update a single document using the collection.updateMany() action.

The following function snippet updates all documents in the items collection by multiplying their quantity values by 10:

const query = {};
const update = { "$mul": { "quantity": 10 } };
const options = { "upsert": false }

return itemsCollection.updateMany(query, update, options)
  .then(result => {
    const { matchedCount, modifiedCount } = result;
    console.log(`Successfully matched ${matchedCount} and modified ${modifiedCount} items.`)
    return result
  })
  .catch(err => console.error(`Failed to update items: ${err}`))

Options

Upsert Documents

If an update operation does not match any document in the collection, you can automatically insert a single new document into the collection that matches the update query by setting the upsert option to true.

The following function snippet updates a document in the items collection that has a name of board game by incrementing its quantity by 5. The upsert option is enabled, so if no document has a name value of "board game" then MongoDB inserts a new document with the name field set to "board game" and the quantity value set to 5:

const query = { "name": "board games" };
const update = { "$inc": { "quantity": 5 } };
const options = { "upsert": true };

itemsCollection.updateOne(query, update, options)
  .then(result => {
    const { matchedCount, modifiedCount, upsertedId } = result;
    if(upsertedId) {
      console.log(`Document not found. Inserted a new document with _id: ${upsertedId}`)
    } else {
      console.log(`Successfully increased ${query.name} quantity by ${update.$inc.quantity}`)
    }
  })
  .catch(err => console.error(`Failed to upsert document: ${err}`))

Field Update Operators

Set the Value of a Field

You can use the $set operator to set the value of a single field without affecting other fields in a document.

{ "$set": { "<Field Name>": <Value>, ... } }

Rename a Field

You can use the $rename operator to change the name of a single field in a document.

{ "$rename": { "<Current Field Name>": <New Field Name>, ... } }

Increment a Value

You can use the $inc operator to add a specified number to the current value of a field. The number can be positive or negative.

{ "$inc": { "<Field Name>": <Increment Number>, ... } }

Multiply a Value

You can use the $mul operator to multiply a specified number with the current value of a field. The number can be positive or negative.

{ "$mul": { "<Field Name>": <Multiple Number>, ... } }

Array Update Operators

Push an Element Into an Array

You can use the $push operator to add a value to the end of an array field.

{ "$push": { "<Array Field Name>": <New Array Element>, ... } }

Pop the Last Element out of an Array

You can use the $pop operator to remove either the first or last element of an array field. Specify -1 to remove the first element and 1 to remove the last element.

{ "$pop": { "<Array Field Name>": <-1 | 1>, ... } }

Add a Unique Element to an Array

You can use the $addToSet operator to add a value to an array field if that value is not already included in the array. If the value is already present, $addToSet does nothing.

{ "$addToSet": { "<Array Field Name>": <Potentially Unique Value>, ... } }

Remove Elements from an Array

You can use the $pull operator to remove all instances of any values that match a specified condition from an array field.

{ "$pull": { "<Array Field Name>": <Value | Expression>, ... } }