Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
MongoDB - Field Update Operators
Next article icon

MongoDB Update Operators

Last Updated : 05 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
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.


Next Article
MongoDB - Field Update Operators
author
sachinparmar98134
Improve
Article Tags :
  • MongoDB
  • Geeks Premier League
  • Databases
  • Geeks Premier League 2023

Similar Reads

  • MongoDB - Field Update Operators
    MongoDB offers a range of powerful field update operators that enable efficient modification of specific fields within documents. These operators allow developers to update specific fields in documents without rewriting the entire document, thus improving performance and operational efficiency. By g
    5 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 Operator
    3 min read
  • MongoDB - $pop Operator
    The $pop operator in MongoDB is designed for managing array fields by removing either the first or last element of the array. This operator simplifies the process of maintaining array size and managing data in scenarios where a fixed number of elements is required. In this article, We will learn abo
    4 min read
  • MongoDB $subtract Operator
    MongoDB’s $subtract operator is an essential tool in the aggregation pipeline, allowing users to perform subtraction operations on numbers, dates, and even date-time calculations. This powerful operator simplifies arithmetic operations within the aggregation pipeline and enhances MongoDB's ability t
    4 min read
  • MongoDB $pow Operator
    MongoDB's $pow operator is a powerful tool within the aggregation framework which is designed to compute exponentiation operations directly on numeric fields. In this article, We will learn about the MongoDB $pow Operator in detail by understanding various examples and so on. MongoDB $pow OperatorTh
    4 min read
  • MongoDB $pull Operator
    The $pull operator in MongoDB is a powerful update operator used to remove all instances of a specified value or values from an array. This operator is particularly useful for modifying arrays within documents without retrieving and updating the entire array manually. In this article, We will learn
    5 min read
  • MongoDB $push Operator
    The $push operator in MongoDB is a powerful tool used to update arrays within documents. It appends the entire array as a single element. To add each element of the array individually, the $each modifier can be used alongside $push. In this article, We will learn about the MongoDB $push Operator by
    5 min read
  • MongoDB $sqrt Operator
    MongoDB provides different types of arithmetic expression operators that are used in the aggregation pipeline stages $sqrt operator is one of them. This operator is used to find the square root of a positive number and returns the result as a double. Syntax: { $sqrt: <number> } Here, the numbe
    2 min read
  • MongoDB $size Operator
    When working with data in MongoDB, arrays are a fundamental data type used to store multiple values in a single field. Whether we're handling lists of tags, categories, or other collections, it's often necessary to determine the size of an array. MongoDB provides the $size operator to help us effici
    5 min read
  • MongoDB - $pullAll Operator
    MongoDB $pullAll operator is a crucial tool for efficiently managing arrays within MongoDB documents. It allows users to remove all instances of specified values from an array and provides a direct way to update array fields. In this article, We will learn about the MongoDB $pullAll Operator by unde
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences