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

MongoDB – Update() Method

Last Updated : 17 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 about MongoDB update() by understanding various examples in detail.

MongoDB update()

The MongoDB update() method is a method that is used to update a single document or multiple documents in the collection. When the document is updated the _id field remains unchanged.

The db.collection.update() method updates a single document by default. To update all documents that match the given query, use the multi: true option. Include the option “multi: true“.

Note: In MongoDB, the update() method has been deprecated in favor of using updateOne() or updateMany() depending on your specific use case.

Syntax

db.COLLECTION_NAME.update({SELECTION_CRITERIA}, {$set:{UPDATED_DATA}}, {
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ],
hint: <document|string>
})

Explanation: This MongoDB update operation updates documents that match the selection criteria with the specified updated data. Here’s an explanation of the parameters used:

  • COLLECTION_NAME: The name of the collection to update.
  • SELECTION_CRITERIA: The criteria to select which documents to update.
  • UPDATED_DATA: The new data to set for the selected documents.
  • upsert: (Optional) If set to true, creates a new document when no document matches the selection criteria.
  • multi: (Optional) If set to true, updates multiple documents that match the selection criteria. Default is false, which updates only the first matching document.
  • writeConcern: (Optional) Specifies the level of write concern for the operation.
  • collation: (Optional) Specifies the collation for string comparisons.
  • arrayFilters: (Optional) Filters to determine which elements to modify in an array field.
  • hint: (Optional) Forces MongoDB to use a specific index for the operation.

Examples of MongoDB update

Let set up an environment:

To understand MongoDB update we need a collection called students on which we will perform various operations and queries.

[
{ _id: 1, name: "Alice", age: 25, grades: [
{ grade: "Maths", score: 80 },
{ grade: "Science", score: 85 }
]
},
{ _id: 2, name: "Bob", age: 30, grades: [
{ grade: "Maths", score: 75 },
{ grade: "Science", score: 90 }
]
},
{ _id: 3, name: "Charlie", age: 35, grades: [
{ grade: "Maths", score: 95 },
{ grade: "Science", score: 88 }
]
}
]

Example 1: Update a Single Document

Write a query to update the age of a student named Alice to 26 in the “students” collection.

db.students.updateOne(
{ name: "Alice" },
{ $set: { age: 26 } }
)

Output:

[
{
_id: 1,
name: 'Alice',
age: 26,
grades: [ { grade: 'Maths', score: 80 }, { grade: 'Science', score: 85 } ]
},
{
_id: 2,
name: 'Bob',
age: 30,
grades: [ { grade: 'Maths', score: 75 }, { grade: 'Science', score: 90 } ]
},
{
_id: 3,
name: 'Charlie',
age: 35,
grades: [ { grade: 'Maths', score: 95 }, { grade: 'Science', score: 88 } ]
}
]

Example 2: Use Update Operator Expressions ($inc and $set)

Write a query to increment the age of a student named Bob by 1 in the “students” collection.

db.students.updateOne(
{ name: "Bob" },
{ $inc: { age: 1 } }
)

Output:

[
{
_id: 1,
name: 'Alice',
age: 26,
grades: [ { grade: 'Maths', score: 80 }, { grade: 'Science', score: 85 } ]
},
{
_id: 2,
name: 'Bob',
age: 31,
grades: [ { grade: 'Maths', score: 75 }, { grade: 'Science', score: 90 } ]
},
{
_id: 3,
name: 'Charlie',
age: 35,
grades: [ { grade: 'Maths', score: 95 }, { grade: 'Science', score: 88 } ]
}
]

Example 3: Insert a New Document if No Match Exists (Upsert)

Write a query to update the age of a student named Charlie to 30 in the “students” collection. If Charlie does not exist, a new document should be inserted with the specified age.

db.students.updateOne(
{ name: "Charlie" },
{ $set: { age: 30 } },
{ upsert: true }
)

Output:

[
{
_id: 1,
name: 'Alice',
age: 26,
grades: [ { grade: 'Maths', score: 80 }, { grade: 'Science', score: 85 } ]
},
{
_id: 2,
name: 'Bob',
age: 31,
grades: [ { grade: 'Maths', score: 75 }, { grade: 'Science', score: 90 } ]
},
{
_id: 3,
name: 'Charlie',
age: 30,
grades: [ { grade: 'Maths', score: 95 }, { grade: 'Science', score: 88 } ]
}
]

Example 4: Upsert with Duplicate Values

Write a query to update the age of a student named Alice to 26 in the “students” collection. If Alice does not exist, a new document should be inserted with the specified age.

db.students.updateOne(
{ name: "Alice" },
{ $set: { age: 26 } },
{ upsert: true }
)

Output:

[
{
_id: 1,
name: 'Alice',
age: 26,
grades: [ { grade: 'Maths', score: 80 }, { grade: 'Science', score: 85 } ]
},
{
_id: 2,
name: 'Bob',
age: 31,
grades: [ { grade: 'Maths', score: 75 }, { grade: 'Science', score: 90 } ]
},
{
_id: 3,
name: 'Charlie',
age: 30,
grades: [ { grade: 'Maths', score: 95 }, { grade: 'Science', score: 88 } ]
}
]

Example 5: Update with Aggregation Pipeline

Write a query to update the age of a student named Alice by incrementing it by 1 in the “students” collection using an aggregation pipeline in the update operation.

db.students.updateOne(
{ name: "Alice" },
[
{ $set: { age: { $add: ["$age", 1] } } }
]
)

Output:

[
{
_id: 1,
name: 'Alice',
age: 27,
grades: [ { grade: 'Maths', score: 80 }, { grade: 'Science', score: 85 } ]
},
{
_id: 2,
name: 'Bob',
age: 31,
grades: [ { grade: 'Maths', score: 75 }, { grade: 'Science', score: 90 } ]
},
{
_id: 3,
name: 'Charlie',
age: 30,
grades: [ { grade: 'Maths', score: 95 }, { grade: 'Science', score: 88 } ]
}
]

Example 6: Update Elements Match arrayFilters Criteria

Write a query to update the score of a student’s “Maths” grade to 85 using an array filter in the “students” collection

db.students.updateOne(
{ _id: 1 },
{ $set: { "grades.$[elem].score": 85 } },
{ arrayFilters: [ { "elem.grade": { $eq: "Maths" } } ] }
)

Output:

[
{
_id: 1,
name: 'Alice',
age: 27,
grades: [ { grade: 'Maths', score: 85 }, { grade: 'Science', score: 85 } ]
},
{
_id: 2,
name: 'Bob',
age: 31,
grades: [ { grade: 'Maths', score: 75 }, { grade: 'Science', score: 90 } ]
},
{
_id: 3,
name: 'Charlie',
age: 30,
grades: [ { grade: 'Maths', score: 95 }, { grade: 'Science', score: 88 } ]
}
]

Example 7: Update Specific Elements of an Array of Documents

Write a query to update the score of a student’s “Science” grade to 90 using an array filter in the “students” collection

db.students.updateOne(
{ _id: 1 },
{ $set: { "grades.$[elem].score": 90 } },
{ arrayFilters: [ { "elem.grade": { $eq: "Science" } } ] }
)

Output:

[
{
_id: 1,
name: 'Alice',
age: 27,
grades: [ { grade: 'Maths', score: 85 }, { grade: 'Science', score: 90 } ]
},
{
_id: 2,
name: 'Bob',
age: 31,
grades: [ { grade: 'Maths', score: 75 }, { grade: 'Science', score: 90 } ]
},
{
_id: 3,
name: 'Charlie',
age: 30,
grades: [ { grade: 'Maths', score: 95 }, { grade: 'Science', score: 88 } ]
}
]

Conclusion

Overall, MongoDB update operations provide a powerful way to modify documents in a collection. Whether you need to update a single document, multiple documents, or perform complex updates using aggregation pipelines, MongoDB’s update capabilities offer flexibility and efficiency. By mastering these update operations, you can efficiently manage your MongoDB data and tailor it to meet your application’s needs

FAQs on MongoDB update()

What is the difference between updateOne() and updateMany() in MongoDB?

The updateOne() method updates a single document that matches the selection criteria, while updateMany() updates all documents that match the criteria.

Can I use the update() method in MongoDB?

The update() method has been deprecated in favor of updateOne() and updateMany(). It’s recommended to use these newer methods for more specific and clear update operations.

What happens if no documents match the selection criteria and upsert is set to true?

If no documents match the selection criteria and upsert is set to true, a new document will be created using the selection criteria and the update data provided



Previous Article
Next Article

Similar Reads

MongoDB - Update Single Document Using MongoShell
In MongoDB, you can update a single document in the collection using db.collection.updateOne() method. This method updates a document in the collection according to the filter. updateOne() is a mongo shell method, which can updates one document at a time. This method update the first document that satisfies the given condition in the collection. Or
4 min read
MongoDB - Update Multiple Documents Using MongoShell
In MongoDB, you can update multiple documents in the collection using db.collection.updateMany() method. This method updates all the documents in the collection that match the given filter. updateMany() is a mongo shell method, which can update multiple document. This method only accepts the documents that contain update operator expressions. updat
3 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 - 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
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
How to Update MongoDB Field Using Value of Another Field
In the NoSQL database, MongoDB is the most robust and flexible option for managing big data. One common problem that occurs when working with MongoDB is to Update the MongoDB field using the value of another field and change data within our database. In this article, we will learn about How to Update the MongoDB field using the value of another fie
3 min read
MongoDB Update Operators
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 Operator
6 min read
How to Update Multiple Array Elements in MongoDB?
MongoDB, the popular NoSQL database, offers powerful features for manipulating data, including the ability to update multiple array elements within a document. Efficiently updating multiple elements in an array can be important in various scenarios, such as managing user preferences, and handling inventory quantities. In this article, we will learn
3 min read
Connect MongoDB (AWS) from Local Machine using WinSCP and MongoDB Compass
Pre-requisite: AWS and MongoDB In this article, we are going to connect to the Mongo database of the AWS Ubuntu Server instance using WinSCP and learn how to get connected to the server from your local machine using MongoDB Compass.  If you haven't installed a MongoDB server in your AWS EC2 instance then follow the steps present in this article and
4 min read
How to Integrate MongoDB Atlas and Segment using MongoDB Stitch
Data integration has become a crucial component of modern business strategies, allowing companies to enhance the power of data for informed decision-making. According to a recent survey, 85% of businesses believe that integrating data across multiple platforms is important for their success. In this article, We will learn about What is MongoDB Stit
5 min read
MongoDB - Delete Multiple Documents Using MongoDB Shell
The db.collection.deleteMany() method is used to delete multiple documents from a collection in Mongo Shell. This method deletes multiple documents from the collection according to the filter. The deleteMany() is a Mongo shell method, which can delete multiple documents. This method can be used in multi-document transactions. If you use this method
2 min read
Connect MongoDB Atlas Cluster to MongoDB Compass
MongoDB Compass is a free GUI for MongoDB. You might want to connect MongoDB Atlas Cluster to MongoDB Compass to take benefit of the GUI model for database administration. This guide explains how to connect MongoDB Atlas Cluster to MongoDB Compass. The connection process involves obtaining a connection string from MongoDB Atlas, configuring MongoDB
4 min read
MongoDB Shell vs MongoDB Node.JS Driver
MongoDB Shell and the MongoDB Node.js Driver are both tools for interacting with MongoDB, but they serve different purposes and are used in different contexts. Here's a comparison of the two: MongoDB Node.JS DriverA Node.js package called the MongoDB Node.js Driver enables programmatic communication between applications and MongoDB databases. Throu
4 min read
MongoDB Compass vs MongoDB Atlas
MongoDB is a popular NoSQL database known for flexibility and scalability. MongoDB Compass offers a graphical interface for managing databases visually while MongoDB Atlas is a cloud-based service for automated management and scaling of MongoDB databases. In this article, We will learn about the in-depth understanding of the difference between the
5 min read
MongoDB - dropIndexes() Method
MongoDB is a NoSQL documentum type database. By default, _id field is an index in any collection. This indexed value uniquely identifies a document in a collection. Additionally, we can create an index for our requirement for quicker retrieval and improve the performance of a MongoDB operation. At the same time, having too many indexes also an over
3 min read
MongoDB - Bulk.insert() Method
In MongoDB, the Bulk.insert() method is used to perform insert operations in bulk. Or in other words, the Bulk.insert() method is used to insert multiple documents in one go. To use Bulk.insert() method the collection in which data has to be inserted must already exist.  We will discuss the following two types of insertion: Table of Content Unorder
2 min read
MongoDB - Find() Method
MongoDB provides powerful methods for retrieving documents from its collections with find() and findOne() methods. The find() method supports complex queries with various operators and allows specifying which fields to include or exclude and optimizing performance by using indexes. In this article, We will learn about the Find() Method by understan
3 min read
MongoDB - sort() Method
In MongoDB, the sort() method is used to specify the order in which the query returns matching documents from a collection. It allows users to arrange documents in either ascending (1) or descending (-1) order based on the values of one or more fields. In this article, We will learn about the MongoDB sort() method in detail by understanding the var
4 min read
MongoDB updateMany() Method - db.Collection.updateMany()
MongoDB updateMany method is a powerful feature used to update multiple documents in a collection that match a specified filter. This method allows us to apply updates to all documents that meet the criteria defined in the filter. By using MongoDB updateMany developers can efficiently perform bulk update operations. In this article, We will learn a
4 min read
MongoDB - FindOne() Method
MongoDB is a widely used NoSQL database that allows for flexible and scalable data storage. One of its essential methods, findOne() which is used to retrieve a single document from a collection that matches the specified query criteria. This method is particularly useful when we need to fetch one specific document rather than multiple documents. In
4 min read
MongoDB insertMany() Method - db.Collection.insertMany()
MongoDB insertMany() method is a powerful tool for inserting multiple documents into a collection in one operation. This method is highly versatile, allowing for both ordered and unordered inserts, and provides options for customizing the write concern. In this article, We will learn about insertMany() in MongoDB by including its syntax, parameters
7 min read
MongoDB - countDocuments() Method
MongoDB provides various methods to work with documents in a collection and one such method is countDocuments(). This method is particularly useful when we need to count the number of documents that match a specified query filter. In this article, we will learn about the MongoDB countDocuments by understanding the various examples in detail. MongoD
3 min read
MongoDB - FindAndModify() Method
The MongoDB findAndModify method is used to modify and return a single document that matches the given criteria. It can be used to update, remove or insert documents atomically. In this article, We will learn about the MongoDB findandmodify method in detail by understanding various examples and so on. MongoDB findandmodifyThe MongoDB findandmodify
5 min read
MongoDB Remove() Method - db.Collection.remove()
The MongoDB remove() method is used to remove documents from a collection based on specified criteria. It can remove one or all documents matching the query expression. This method offers flexibility in deletion and supports various options like removing only one document and specifying a write concern. In this article, We will learn about MongoDB
4 min read