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

MongoDB – FindAndModify() Method

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

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 findandmodify

  • The MongoDB findandmodify method modifies and returns a single document that matches the given criteria.
  • By default the db.collection.findAndModify(document) method returns a pre-modification document.
  • To return the document with the modifications made on the update, use the new option and set its value to true. It takes a document as a parameter.

Important Points:

  • If we want to find fields of the embedded document, then use the following syntax:

“field.nestedfieldname”: <value>

or

{field: {nestedfieldname: <value>}}

  • The document returned by this method always contains the _id field. If you don’t want the _id field, then set _id:0 in the projection.
  • We can use this method in multi-document transactions.
  • If we are using this method, in shared collection then the query expression must contain an equality condition on the shared key.

MongoDB findandmodify Syntax

db.Collection_name.findAndModify(
{
selection_criteria:<document>,
sort: <document>,
remove: <boolean>,
update: <document>,
new: <boolean>,
fields: <document>,
upsert: <boolean>,
bypassDocumentValidation: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ]
})

Parameters:

  • remove: It is a must if the update field does not exist. If it is true, removes the selected document. The default value is false.
  • update: It is a must if the remove field does not exist. Performs an update of the selected document. The update field employs the same update operators or field: value specifications to modify the selected document.
  • Others are optional.

Optional Parameters:

  • selection_criteria: It specifies the selection criteria for the modification. The query field employs the same query selectors as used in the db.collection.find() method. Although the query may match multiple documents, MongoDB findandmodify will only select one document to modify.
  • sort: Determines which document the operation will modify if the query selects multiple documents. MongoDB findandmodify will modify the first document in the sort order specified by this argument.
  • new: When true, returns the modified document rather than the original. The MongoDB findandmodify method ignores the new option for remove operations. The default is false.
  • fields: A subset of fields to return. The fields document specifies an inclusion of a field with 1, as in the following:
    • fields: { <field1>: 1, <field2>: 1, … }
  • Upsert: The default value of this parameter is false. When it is true it will make a new document in the collection when no document matches the given condition in the update method.
  • writeConcern: It is only used when we do not want to use the default write concern. The type of this parameter is a document.
  • Collation: It specifies the use of the collation for operations. It allows users to specify the language-specific rules for string comparison like rules for lettercase and accent marks. The type of this parameter is a document.
  • arrayFilters: It is an array of filter documents that indicates which array elements to modify for an update operation on an array field. The type of this parameter is an array.

Return:

  • Returns a single pre-modification document. To return the document with the modifications made on the update, use the new option and set it to true.
  • If no document is found for an upsert, which means the command performs an insert, new is false, and the sort option is NOT specified, the method returns null.
  • If no document is found for an upsert, which means the command performs an insert, and new is false, and a sort option is specified, the method returns an empty document {}.

Examples of MongoDB findandmodify Method

Let’s look at some MongoDB FindandModify examples. In the following examples, we are working with:

Database: gfg

Collections: student

Document: Three documents contains name, language they use in coding and the score they got by solve problem on gfg.

Output:

demo database and collection

Example 1: Update Value

We are increasing marks by 4 whose name is vishal.

Query:

db.student.findAndModify({query:{name:"vishal"},update:{$inc:{score:4}}})

Output:

value before query

Output:

findandmodify method example

Example 2: Get the Modified Document

Let’s Find and modify the document for the student with the name “vishal” in the student collection by incrementing the score field by 4. Return the modified document

 db.student.findAndModify({query:{name:"vishal"},
update:{$inc:{score:4}},new:true})

Output:

value before query

Example 3: Update and Return

Let’s Find and update the document for the student with the name “vishal” in the students collection, setting the score to 220. Return the updated document.

db.students.findOneAndUpdate(
{ name: "vishal" },
{ $set: { score: 220 } },
{ returnDocument: "after" }
)

Output:

{
"_id" : ObjectId("60141912de51b19233bcb087"),
"name" : "vishal",
"lang" : "java",
"score" : 220
}

Example 4: Upsert: true

Let’s Update the document for the student with the name “john” in the students collection. If no document matches the query, insert a new document with the name “john”, setting the language to “Python” and the score to 195.

db.students.updateOne(
{ name: "john" },
{ $set: { lang: "Python", score: 195 } },
{ upsert: true }
)

Output:

{
"acknowledged" : true,
"matchedCount" : 0,
"modifiedCount" : 0,
"upsertedId" : ObjectId("60c91514de51b19233bcb08a")
}

Conclusion

Overall, The findAndModify method in MongoDB is a powerful tool for making atomic changes to documents in a collection. It allows you to update, remove, or insert documents while ensuring that no other operations can modify the document in between.

MongoDB findandmodify – FAQs

How does the new option in findAndModify affect the returned document?

The new option, when set to true, returns the modified document after the update operation has been applied. If set to false, it returns the original document before the update.

What is the purpose of the upsert option in findAndModify?

The upsert option, when set to true, allows the findAndModify method to insert a new document if no document matches the query criteria. This is useful for ensuring that a document exists with certain values, even if it didn’t exist before.

Can findAndModify be used in transactions?

Yes, the findAndModify method can be used in multi-document transactions in MongoDB. This allows you to perform complex operations that involve multiple documents while ensuring that the changes are applied atomicall



Previous Article
Next Article

Similar Reads

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 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
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 - 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 - 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 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
MongoDB - findOneAndDelete() Method
The MongoDB findOneAndDelete() is a powerful tool for deleting documents from a collection based on specific criteria. It allows for the deletion of a single document that matches the query filter. In this article, We will learn about MongoDB findOneAndDelete() by understanding various examples and so on. MongoDB findOneAndDelete()The MongoDB findO
4 min read
MongoDB - db.collection.findOneAndUpdate() Method
The MongoDB findOneAndUpdate() method is used to update the first matched document in a collection based on the selection criteria. It offers various options such as sorting, upserting and returning the updated document. In this article, We will learn about MongoDB findOneAndUpdate() in detail by understanding various examples and so on. MongoDB fi
5 min read
MongoDB - db.collection.CreateIndex() Method
MongoDB's createIndex() method is used to create indexes on collections which allows for efficient querying and sorting of data. This method supports various types of indexes like text indexes, 2dsphere indexes, 2d indexes and more. It also provides options to customize the index creation process. In this article, We will learn about the MongoDB cr
7 min read
MongoDB - skip() Method
In MongoDB, the skip() method is used to skip a specified number of documents in a query result. This allows us to control the starting point of the returned results which effectively removes the first n documents from the result set. In this article, We will learn about MongoDB skip() in detail by understanding various examples and so on. MongoDB
4 min read
MongoDB count() Method - db.Collection.count()
MongoDB count() method is a powerful tool for counting documents that match a specified query in a collection. It offers flexibility in filtering documents and can be used to quickly retrieve counts of documents based on various criteria. In this article, We will learn about the MongoDB count() Method by understanding various examples in detail. Mo
3 min read
MongoDB dropIndex() Method
In MongoDB, indexes are data structures that store a small portion of the collection’s data in an easy-to-traverse form. The dropIndex() method provides a way to drop or delete an index from a collection in MongoDB. It is important to note that we cannot drop the default index on the _id field using this method. In this article, We will learn about
4 min read
MongoDB - getIndexes() Method
In MongoDB, the getIndexes() method is used to retrieve information about the existing indexes on a specified collection. This method returns an array of documents that describe each index, including hidden indexes. In this article, We will explore the getIndexes() method in MongoDB, its syntax, usage and examples. MongoDB getIndexes() MethodIn Mon
3 min read
MongoDB - copyTo() Method
MongoDB copyTo() method is used to duplicate the contents of one collection into another collection within the same database. It's like making a copy of a file on your computer to another location. In this article, We will learn about MongoDB copyTo() Method with the help of examples and so on. MongoDB copyTo() MethodThe copyTo() method in MongoDB
3 min read
MongoDB insertOne() Method - db.Collection.insertOne()
insertOne() method in MongoDB is a powerful tool for inserting a single document into a collection. This method ensures that each document added to the collection is assigned a unique _id if one is not provided, thus maintaining the integrity and uniqueness of the data. In this article, We will learn about the MongoDB insertOne() Method by understa
3 min read
MongoDB - bulkWrite() Method
The bulkWrite() method in MongoDB is a powerful tool that allows for the execution of multiple write operations with a single command. This method is particularly useful for efficiently performing batches of operations, reducing the number of round trips to the database server and thus improving performance. In this article, We will learn about the
8 min read
MongoDB - db.collection.createIndexes() Method
The createIndexes() method in MongoDB allows us to create one or more indexes on a specified collection based on the fields in the documents. Indexes in MongoDB enhance query performance by speeding up data retrieval operations. In this article, We will learn about MongoDB createIndexes() by understanding how to create along with the examples and s
7 min read
MongoDB - Distinct() Method
The distinct() method in MongoDB is a powerful tool used to find unique values for a specified field across a single collection. By retrieving all distinct values associated with a specific key, this method helps eliminate duplicates and enables better analysis and reporting on the dataset. In this article, We will learn about the MongoDB Distinct(
3 min read
MongoDB - Insert() Method
In MongoDB, the insert() method was used to add documents to a collection it allows us to insert both single and multiple documents at once. However, since MongoDB version 3.2, the insert() method has been deprecated. It is now recommended to use more specialized methods like insertOne(), insertMany() and bulkWrite() In this article, We will learn
5 min read
MongoDB - updateOne() Method
MongoDB's updateOne() method provides a powerful way to update a single document in a collection based on specified criteria. This method is particularly useful when Accuracy is needed in modifying specific documents without affecting others. In this article, We will learn about MongoDB updateOne() by understanding various examples and so on. Mongo
6 min read
MongoDB - limit() Method
The limit() method in MongoDB is a powerful tool used to control the number of documents returned in a query result. It is particularly beneficial when working with large collections as it allows for the restriction of result set sizes thereby improving performance and reducing client load. In this article, We will learn about the limit() method in
3 min read