The Wayback Machine - https://web.archive.org/web/20240711201125/https://www.geeksforgeeks.org/mongodb-update-operators/
Open In App

MongoDB Update Operators

Last Updated : 05 Jul, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

MongoDB update operators offer powerful tools for modifying documents within a collection which provides flexibility and efficiency in database operations. From setting and unsetting fields to manipulating arrays and applying bitwise operations. In this article, we will understand different Update Operators which is used in MongoDB.

Update Operators

  • Update operators in MongoDB are special commands used to modify documents within a collection. They provide powerful functionalities for updating specific fields, arrays, and embedded documents and ensuring efficient data manipulation without needing to retrieve and replace entire documents.
  • MongoDB’s update operators include $set for setting or updating field values, $unset for removing fields, $inc for incrementing numeric values, $addToSet for adding unique elements to arrays, $push for appending elements to arrays, $pull for removing specific elements from arrays, $currentDate for setting fields to the current date/time, and more.

1. Fields

MongoDB allows us to update the individual fields within a document.

Modifier

Description

$set

Set the value of a field. The field is created if it does not exist, and so can be used for dynamic updates or adding new fields to documents.

$unset

The entire field can be removed from the document without having to remove invalid data, allowing greater security.

$rename

If restructuring document schema requires a change in field name, it can be renamed while still maintaining existing value.

2. Arrays

The following modifiers are useful for manipulating array data.

Modifier

Description

$addToSet

Adds unique elements to an array if they are missing and doesn’t add duplicate values.

$pop

Trims an array, dropping either the first or last element.

$pull

Allows elements in an array that match a particular query to be removed selectively based on some conditions.

$push

Adds an element to the end of an array, versatile and supports adding more than one element at a time.

3. Modifiers

MongoDB offers modifiers that bring additional functionality to the update operation.

Modifier

Description

$inc

Adds to the current value of a field, particularly effective for numeric fields. Supports implementing counters or tracking numerical changes.

$currentDate

Setting the value of a field to current date and time, used for timestamping operations or making sure that each operation is able to reflect its last update.

$setOnInsert

During an insert operation, only particular fields are specified. These will be added upon a successful insert but have no effect during any update thereafter.

4. Bitwise

Sub-Operator

Description

$and

Perform a bitwise AND operation

$or

Perform a bitwise OR operation

$xor

Perform a bitwise XOR operation

$not

Perform a bitwise NOT operation

Example: Update Operators

Example 1: Using $currentDate

Imagine you have a collection of blog posts, and when editing. This timestamping operation can be assisted by the $currentDate operator.

// Before Update
db.blogPosts.findOne({ _id: postId })

// Update using $currentDate
db.blogPosts.update(
{ _id: postId },
{ $currentDate: { lastModified: true } }
)

// After Update
db.blogPosts.findOne({ _id: postId })

Output:

// Before Update
{
_id: ObjectId("5fd0c7b86ee8a1475896a117"),
title: "MongoDB Update Operators",
content: "Introduction to MongoDB update operators...",
lastModified: ISODate("2023-01-01T12:00:00Z")
}
// After Update
{
_id: ObjectId("5fd0c7b86ee8a1475896a117"),
title: "MongoDB Update Operators",
content: "Introduction to MongoDB update operators...",
lastModified: ISODate("2023-12-13T15:30:00Z")
}

Before Updates

// Retrieve a blog post with a specific ID
db.blogPosts.findOne({ _id: postId })

Before doing any editing, this line first gets a blog post from the MongoDB collection named blogPosts. It does this by looking for a document with the specific _id (a unique identifier), which each blog post has.

Update using $currentDate

// Update the "lastModified" field to the current date and time
db.blogPosts.update({ _id: postId }, { $currentDate: { lastModified: true } })

This line updates a particular post in the blogPosts collection. This update is focused on the document with a given _id (unique identifier). The update operation uses the $currentDate operator to set its value of lastModified field into current date and time. In fact, it’s like adding a time stamp to the blog post showing when it was last modified.

After Update

// Retrieve the updated blog post
db.blogPosts.findOne({ _id: postId })

Following the update, this line retrieves again to observe how things have changed. Now, the lastModified field should be set to today’s date and time so that people can see when this blog post was last altered.

Example 2 : Using $inc and $set

Consider a scenario where you have a collection of products, and you want to update the inventory count and set a new discount for a specific product.

// Before Update
db.products.findOne({ _id: productId })

// Update using $inc and $set
db.products.update(
{ _id: productId },
{
$inc: { inventory: -5 }, // Decrement inventory by 5 units
$set: { discount: 0.1 } // Set a new discount of 10%
}
)

// After Update
db.products.findOne({ _id: productId })

Output:

// Before Update
{
_id: ObjectId("5fd0c7b86ee8a1475896a118"),
name: "Smartphone XYZ",
inventory: 100,
discount: 0.05
}
// After Update
{
_id: ObjectId("5fd0c7b86ee8a1475896a118"),
name: "Smartphone XYZ",
inventory: 95,
discount: 0.1
}

Before Updates

// Retrieve product information with a specific ID
db.products.findOne({ _id: productId })

This line retrieves a product document from the MongoDB collection products. It seeks a document with exactly the same_id as productId.

Update using $inc and $set

// Update the product with specified changes
db.products.update(
{ _id: productId },
{
$inc: { inventory: -5 }, // Decrease inventory by 5 units
$set: { discount: 0.1 } // Set a new discount of 10%
}
)

This block updates a particular product in the products collection. The product is identified by its unique_id. The update operation uses two operators:

  • $inc: This operator increments (or in this case, decrements with a negative value) the current value of a field. In this example, it decreases the inventory field by 5 units.
  • $set: This operator sets the value of a field. Here, it sets the discount field to 0.1, representing a new discount of 10%.

After Updates

// Retrieve the updated product information
db.products.findOne({ _id: productId })

Following the update, this line retrieves the same product to see the changes. Now, the inventory should be reduced by 5 units, and the discount should reflect the new value of 0.1.

This code is effectively updating a product’s information in MongoDB. It decreases the inventory by 5 units and sets a new discount of 10%, providing a practical example of how to modify data in a MongoDB collection.

Conclusion

MongoDB Updatе Opеrators is еffеctivе data managеmеnt. Thе operators providеs a powerful toolkit for your data to meet evolving requirements. Whether it’s updating fields, arrays, or introducing new elements, MongoDB’s updatе capabilitiеs offеr flexibility and precision.

FAQs on MongoDB Update Operators

How does the $set operator function in MongoDB updates?

The $set operator in MongoDB is used to assign a specific value to a field within a document. It can create new fields if they do not exist and update existing fields with new values.

How does the $addToSet operator differ from $push in MongoDB?

$addToSet adds elements to an array only if they are not already present, ensuring uniqueness. $push, on the other hand, adds elements to the end of an array regardless of their presence.

When should you use the $inc operator in MongoDB?

The $inc operator is ideal for updating numerical fields by incrementing or decrementing their values. It’s commonly used for counters or updating numeric properties like inventory levels.

What is the purpose of the $currentDate operator in MongoDB updates?

The $currentDate operator sets the value of a field to the current date and time. It’s useful for timestamping operations, ensuring that documents reflect their last update time accurately.



Similar Reads

MongoDB - Field Update Operators
MongoDB, a popular NoSQL database, provides a variety of field update operators that simplify data manipulation tasks. These operators allow developers to perform specific updates on fields within documents without needing to rewrite entire documents. In this article, We will learn about the several Field Update Operators in MongoDB with the help o
5 min read
How to update single and multiple documents in MongoDB using Node.js ?
MongoDB the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This format of storage is called BSON (similar to JSON for
2 min read
Difference Between findAndModify and Update in MongoDB?
MongoDB, with its flexible document-based data model, offers a range of methods for updating data within collections. Two of the most commonly used methods, findAndModify and update, each has its unique strengths and purposes. Understanding the differences between these methods can significantly impact the efficiency and effectiveness of our MongoD
4 min read
How to Update the _id of MongoDB Document?
In MongoDB, the _id field serves as a unique identifier for each document in a collection. While MongoDB automatically generates _id values for documents upon insertion, there are scenarios where we might need to update the _id of a document. In this article, We will learn about How to update the _id of one MongoDB Document with the help of example
3 min read
How to Update Objects in a Document's Array in MongoDB?
Imagine we are managing a database with a large collection of documents, each containing arrays of nested objects. Now, here the challenge comes by updating specific objects within those arrays without altering the rest of the document. This is a common scenario in MongoDB, a powerful NoSQL database. In this article, we'll learn about updating obje
4 min read
How to Update the First Object in an Array in MongoDB
MongoDB, a popular NoSQL database, offers powerful features for handling complex data structures. One common scenario is updating specific elements within arrays stored in documents. In this guide, we'll focus on updating the first object in an array within a MongoDB document. We'll cover the concepts step by step, providing examples and outputs to
3 min read
How to Update Deeply Nested Array in MongoDB/ Mongoose ?
In MongoDB/Mongoose, updating deeply nested arrays can be challenging due to the nested structure. This article will explore various approaches to update deeply nested arrays efficiently using both MongoDB queries and Mongoose methods. Explaining each approach one by one below: Table of Content Using MongoDB's Update OperatorsUsing Mongoose's findB
2 min read
How to Update a Document in MongoDB using NodeJS?
Updating documents in MongoDB is a basic operation for maintaining and managing your database effectively. Node.js, combined with MongoDB, offers a powerful and flexible environment for performing database operations. In this article we will learn how to update a document from a MongoDB collection, starting from connecting the MongoDB to NodeJS, cr
4 min read
MongoDB - Update() Method
MongoDB update operations allow us to modify documents in a collection. These operations can update a single document or multiple documents based on specified criteria. MongoDB offers various update operators to perform specific actions like setting a value, incrementing a value or updating elements within arrays. In this article, We will learn abo
7 min read
MongoDB Bitwise Update Operator
The MongoDB Bitwise Update Operator allows for efficient manipulation of integer fields within MongoDB documents through bitwise operations. In this article, We will learn about the MongoDB Bitwise Update Operator in detail by understanding various examples in detail. MongoDB Bitwise Update OperatorMongoDB Bitwise Update Operator allows performing
3 min read