Find and Modify in MongoDB

Ratings:
(4)
Views:0
Banner-Img
  • Share this blog:

MongoDB findAndModify() method modifies and returns a single document based upon the selection criteria entered. The returned document does not show the updated content by default. If the records matching the criteria does not exist in the database, a new record will be inserted if the upsert is set.

syntax:

db.collection.findAndModify({
 query: <document>,
 sort: <document>, 
 new: <boolean>,
 fields: <document>,
 upsert: <boolean>
})

Find And Modify MongoDB

-If the entered selection criteria does not fetch any document and if upsert is set to true, then the specified values are inserted and a new document is created.

-If the entered selection criteria does not fetch any document while performing update or remove operations, the output returned is null.

-If the new option is set to false and sort operation is not mentioned, the output returned is null.

-If the new option is set to false and sort operation is specified, the output is empty.

Examples demonstrating the usage of the find And Modify API.

Create some test data to start with.

create a new car document with name, color, car no (cno), speed and manufactured country(mfdcountry) fields through the mongo console.

db.car.insert(
[
{ _id: 1, name: "Alto", color: "Red",cno: "H410",speed:40,mfdcountry: "India"},
{ _id: 2, name: "Polo", color: "White",cno: "H411",speed:45,mfdcountry: "Japan" },
{ _id: 3, name: "Audi", color: "Black",cno: "H412",speed:50,mfdcountry: "Germany" }
]
)

Verify that the data was actually inserted using find :

db.car.find()
{ "_id" : 1, "name" : "Alto", "color" : "Red", "cno" : "H410", "speed" : 40, "mfdcountry" : "India" }
{ "_id" : 2, "name" : "Polo", "color" : "White", "cno" : "H411", "speed" : 45, "mfdcountry" : "Japan" }
{ "_id" : 3, "name" : "Audi", "color" : "Black", "cno" : "H412", "speed" : 50, "mfdcountry" : "Germany" }

Moving on to the actual usage of find and modify, we depict different possibilities.

Case 1: The document exists in the database

db.car.findAndModify({
query: { name: "Alto" },
sort: { cno: 1 },
update: { $inc: { speed: 10 } },
})

The query finds a document in the car collection where the name field has the value Alto.

The sort orders the results of the query in ascending order. If multiple documents meet the query condition, the method will select for modification the first document as ordered by this sort.

Aspired to become an Mongo DB?
Explore the post to discover the know-hows on Mongo DB Training.

The update increments the value of the speed field by 10.

The method returns the original document selected for this update :

Output:

{
"_id" : 1,
"name" : "Alto",
"color" : "Red",
"cno" : "H410",
"speed" : 40,
"mfdcountry" : "India"
}

Case 2: The new option set to true (returns the updated data set)

db.car.findAndModify({
query: { name: "HondaCity", color: "Silver", cno:"H415" ,speed: 25 },
sort: { cno: 1 },
update: { $inc: { speed: 20 } },
upsert: true,
new: true
})

Output:

{
"_id" : ObjectId("546c9f347256eabc40c9da1c"),
"cno" : "H415",
"color" : "Silver",
"name" : "HondaCity",
"speed" : 45
}
Note: that speed is being displayed as 45 which is the updated value since we set new to be true. If this is not set, the speed field will be shown as 20 , the old value though it gets updated in the database.
 
Case 3: The upsert is set to true
 
db.car.findAndModify({
query: { name: "WagonR" },
sort: { cno: 1 },
update: { $inc: { speed: 5 } },
upsert: <strong>true</strong>
})
 
Output:
db.car.find();
{ "_id" : 1, "name" : "Alto", "color" : "Red", "cno" : "H410", "speed" : 50, "mfdcountry" : "India" }
{ "_id" : 2, "name" : "Polo", "color" : "White", "cno" : "H411", "speed" : 45, "mfdcountry" : "Japan" }
{ "_id" : 3, "name" : "Audi", "color" : "Black", "cno" : "H412", "speed" : 50, "mfdcountry" : "Germany" }
{ "_id" : ObjectId("546c7c7d6be0faf69ee36546"), "name" : "WagonR", "speed" : 5 }
 
The car name with WagonR is not in the db hence a new document is created in database. The method returns an empty document { } if the sort option is specified. If sort option is not included then the method returns null.
 

Apart from these, this can also be used for doing a Sort and Remove operation.

If the remove field is set to true, the car name with the specified criteria will be removed from the database.

db.car.findAndModify(
{
query: { name: "Alto" },
sort: { cno: 1 },
remove: true
}
)

Output:

{
"_id" : 1,
"name" : "Alto",
"color" : "Red",
"cno" : "H410",
"speed" : 50,
"mfdcountry" : "India"
}

The remove field is set to true the document with the name “Alto” gets deleted from the database.

For indepth understanding click on

You liked the article?

Like : 0

Vote for difficulty

Current difficulty (Avg): Medium

Recommended Courses

1/1

About Author
Authorlogo
Name
TekSlate
Author Bio

TekSlate is the best online training provider in delivering world-class IT skills to individuals and corporates from all parts of the globe. We are proven experts in accumulating every need of an IT skills upgrade aspirant and have delivered excellent services. We aim to bring you all the essentials to learn and master new technologies in the market with our articles, blogs, and videos. Build your career success with us, enhancing most in-demand skills in the market.


Stay Updated


Get stories of change makers and innovators from the startup ecosystem in your inbox