Navigation

Update Documents

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.

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" }
}
}
}

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 ...
}

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 lego to blocks and adds a price of 20.99:

const query = { "name": "lego" };
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}`))

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

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

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>, ... } }

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

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

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>, ... } }

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>, ... } }

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

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

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>, ... } }

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>, ... } }

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>, ... } }

You can use the $[] (All Positional Update) operator to update all elements in an array field:

Example

Consider a students collection that describes individual students in a class. The documents each include a grades field that contains an array of numbers:

{ "_id" : 1, "grades" : [ 85, 82, 80 ] }
{ "_id" : 2, "grades" : [ 88, 90, 92 ] }
{ "_id" : 3, "grades" : [ 85, 100, 90 ] }

The following update operation adds 10 to all values in the grades array of every student:

await students.updateMany(
{},
{ $inc: { "grades.$[]": 10 } },
)

After the update, every grade value has increased by 10:

{ "_id" : 1, "grades" : [ 15, 92, 90 ] }
{ "_id" : 2, "grades" : [ 18, 100, 102 ] }
{ "_id" : 3, "grades" : [ 15, 110, 100 ] }

You can use the $[element] (Filtered Positional Update) operator to update specific elements in an array field based on an array filter:

Example

Consider a students collection that describes individual students in a class. The documents each include a grades field that contains an array of numbers, some of which are greater than 100:

{ "_id" : 1, "grades" : [ 15, 92, 90 ] }
{ "_id" : 2, "grades" : [ 18, 100, 102 ] }
{ "_id" : 3, "grades" : [ 15, 110, 100 ] }

The following update operation sets all grade values greater than 100 to exactly 100:

await students.updateMany(
{ },
{
$set: {
"grades.$[grade]" : 100
}
},
{
arrayFilters: [{ "grade": { $gt: 100 } }]
}
)

After the update, all grade values greater than 100 are set to exactly 100 and all other grades are unaffected:

{ "_id" : 1, "grades" : [ 15, 92, 90 ] }
{ "_id" : 2, "grades" : [ 18, 100, 100 ] }
{ "_id" : 3, "grades" : [ 15, 100, 100 ] }
Give Feedback