MongoDB provides the update() method to update the documents of a collection. To update only the specific documents, you need to add a condition to the update statement so that only selected documents are updated. In this article, we will understand how to update a document in MongoDB using the update() method, save () method, updateOne() method and updateMany() method with examples for each. We will also look at the differences between each of these methods. Updating Single document Syntax: db.collection.update(query, update, options) Use the update method  Specify the condition to be used to update the document. In the below example, we need to update the document which has the Employee id as 100. Use the $set operator to update the values Choose the Field Name that needs to be updated and enter the new values accordingly – Employee_Name =”Daniel Morales”db.Employees.update( {"Emp_ID" :100}, {$set:{"Employee_Name" :"Daniel Morales"}}); WriteResult({"nMatched": 1,  "nUpserted: 0, "nModified":1 })Updating Multiple documents Syntax: db.collection.update(query, update, options) For updating multiple documents at the same time in MongoDB, we need to use the multi option or else by default only one document is updated at a time.The below example shows how to update many documents. In this example, we are going to first find the document which has the Emp_ID id as "1" and then change the Emp_ID from 1 to 21 and Employee_Name to “Nandan Kumar”. Use the update method  Specify the condition which should be used for updating the document. In the below example, we need to update the document which has the Employee id as 1. Use the $set operator to update the values Choose the Field Name(s) that needs to be updatedand enter the new values accordingly – Employee_Name =”Nandan Kumar” Emp_ID = 21db.Employees.update({ Emp_ID : 1},{$set :{"Employee_Name" : "Nandan Kumar"," Emp_ID" : 21}})MongoDB save() Method  The db.collection.save() method is used to update an existing document or insert a new document Syntax: db.collection.save() db.Employees.save( {Emp_ID : 21000 , Employee_Name : "Anshu", Salary:20000 } ); WriteResult({“ nInserted" : 1 })The save() method returns a WriteResult object which contains the status of the insert or update operation. During the insert, the shell will create the _id field with a unique ObjectId value, as verified by the inserted document:db.Employees.find(); {"_id" : ObjectId("5da78973835b2f1c75347a83"),"Emp_ID" : 21000 , "Employee_Name" : "Anshu", "Salary":20000 }In the below example, save() method performs an insert since the document passed to the method does not contain the _id field so it creates a new document . Note -  If the document doesn’t contain an _id field, then the save() method calls the insert() method. db.Employees.save({_id:2400, Emp_ID : 21000 , Employee_Name : "Anshu", Salary:20000 } ); WriteResult({"nMatched": 0,  "nUpserted: 1, "nModified":0,”_id”:2400})The save() method performs an update with upsert: true since the document contains an _id field:  db.Employees.save({_id:2400, Emp_ID : 21000 , Employee_Name : "Anshu", Salary:20000 } ); WriteResult({"nMatched": 1,  "nUpserted: 1, "nModified":0 })Note -  If the document already contains an _id field, then the save() method is equivalent to an update with the upsert option set to true and the query predicate on the _id field. Updating Single and Multiple Values in MongoDB documents by using methods  -updateOne, updateManywith examples : MongoDB updateOne() method This method updates a single document within a collection matching the filter or condition. Syntax The syntax of updateOne() method is − db.collection.updateOne(<filter>, <update>) Example> db.Employees.updateOne( {First_Name: 'Nandan'}, { $set: { Age: '30',e_mail: 'nandan@gmail.com'}} ) { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 0 }MongoDB updateMany() method The updateMany() method updates all the documents within a collection based on the filter or condition . Syntax : The syntax of updateMany() method is − db.collection.updateMany(<filter>, <update>) Example>db.Employees.updateMany( {Age:{$gt:"25"}},  { $set:{Age:'12'}} ) {"acknowledged":true,"matchedCount":2,"modifiedCount":2}Using the find command, you can retrieve the contents of the documents:> db.Employees.find() { "_id" : ObjectId("6fd6636870fb13eec3963bf5"), "First_Name" : "Nandan", "Last_Name" : "Kumar", "Age" : "12", "e_mail" : "nandan@gmail.com", "phone" : "8000012345 { "_id" : ObjectId("6fd6636870fb13eec3963bf6"), "First_Name" : "Chris", "Last_Name" : "Goel", "Age" : "12", "e_mail" : "chris@gmail.com", "phone" : "8000054321" } { "_id" : ObjectId("6fd6636870fb13eec3963bf7"), "First_Name" : "Praveen", "Last_Name" : "Sharma", "Age" : "21", "e_mail" : "praveen@gmail.com", "phone" : "9000011111" }What If the update operation doesn’t match documents in collection? If the update operation doesn't match any documents in the collection, it can automatically insert a new document into the collection which matches the update query by setting the upsert option as true.db.Employees.update( {type:"FullTime"}, {$set:{salary:20000}}, {upsert : true} )WriteResult ({"nMatched": 0,  "nUpserted: 1, "nModified":1 })   You can also see the upsert getting reflected in the Write Result of the above operation. upsert operation in MongoDB is used to save documents into collection . If the document matches query criteria, then it will perform an update operation or else it will insert a new document into the collection. Difference between db.collection.update() , db.collection.update One() and db.collection.update Many() The difference is that update() by default, modifies only one document based on the specified filter. However, the user can modify all the documents by adding the modifier {multi: true} . This command works as both updateOne and updateMany command. db.Employees.update (    { "joinYear ": "2020" },    {      $set: { "bonusEligiblity": "False" }, } )Here, it will update only first document which matches the condition.db.Employees.update ( { "joinYear ": "2020" }, {$set: { "bonusEligiblity": "False" },    }, { multi: true } // Additional Parameter )Here, by adding the parameter – multi: true it works as updateMany() and updates all the documents matching the condition .db.collection.updateOne() --> method to update only one document in a collection.db.Employees.update (    { "joinYear ": "2020" },    {      $set: { "bonusEligiblity": "False" }, // Here multiple parameters can also be updated } )This update commands use the joinDate =2020 as a filter (match the query) in the collection “Employees”.$set operator (called as update operator) updates the value of the bonusEligiblity to False.You can also update multiple parameters but they need to be separated by a comma (,). E.g.$set: { "bonusEligiblity": "False" , “emp_status : ”New”},db.collection.updateMany() --> method to update multiple document in a collection matching the specified conditiondb.Employees.updateMany( { "joinYear": "2020" }, {$set: { "bonusEligiblity": "False" },   } )Here, ALL the documents having joinYear =2020 get updated to bonus Eligiblity= “False” What If the update operation doesn’t match documents in collection? If the update operation doesn't match any documents in the collection, it can automatically insert a new document into the collection which matches the update query by setting the upsert option as true.db.Employees.update(     {type:"FullTime"},     {$set:{salary:20000}}, {upsert : true} )WriteResult({"nMatched": 0, "nUpserted: 1, "nModified":1 }) You can also see the upsert getting reflected in the WriteResult of the above operation.upsert operation in MongoDB is used to save documents into collection.If the document matches query criteria then it will perform an update operation or else it will insert a new document into the collection.upsert also partially updates an object in MongoDB so that the new object will overlay or merge with the existing one.In brief, upsert is also used to update a document with the contents of another document, but only updates the fields that are absent and completely ignore the fields that are already set.ConclusionTo summarize, MongoDB has methods: update() and save() which are used to update documents into a collection. The update() method updates the values in the existing document while the save() method is used to insert a new document or update an existing document if it already contains an _id field The parameters in the document.update() method is a condition for which document needs to be updated, and the next is the update operation which needs to be performed. db.collection.update (query, update, options) In this article, we have gone over the update() method, save () method, updateOne() method and updateMany() method with examples for each. We have also explored the upsert function. Hope this has been useful. The MongoDB course will get you familiar with the popular NoSQL database and arm you with the essential skills to start using Mongo to power your software application. Happy coding! Your one-stop-shop for MongoDB is just a click away. Access our live online training and find easy solutions to all your queries here. # How to Update Document in MongoDB 8K • by Nandan Kumar • 01st Aug, 2020 • Last updated on 15th Mar, 2021 • 7 mins read MongoDB provides the update() method to update the documents of a collection. To update only the specific documents, you need to add a condition to the update statement so that only selected documents are updated. In this article, we will understand how to update a document in MongoDB using the update() method, save () method, updateOne() method and updateMany() method with examples for each. We will also look at the differences between each of these methods. ## Updating Single document Syntax: db.collection.update(query, update, options) 1. Use the update method 2. Specify the condition to be used to update the document. In the below example, we need to update the document which has the Employee id as 100. 3. Use the$set operator to update the values
4. Choose the Field Name that needs to be updated and enter the new values accordingly –
Employee_Name =”Daniel Morales”
db.Employees.update(
{"Emp_ID" :100},
{$set:{"Employee_Name" :"Daniel Morales"}}); WriteResult({"nMatched": 1, "nUpserted: 0, "nModified":1 }) ## Updating Multiple documents Syntax: db.collection.update(query, update, options) For updating multiple documents at the same time in MongoDB, we need to use the multi option or else by default only one document is updated at a time. The below example shows how to update many documents. In this example, we are going to first find the document which has the Emp_ID id as "1" and then change the Emp_ID from 1 to 21 and Employee_Name to “Nandan Kumar”. 1. Use the update method 2. Specify the condition which should be used for updating the document. In the below example, we need to update the document which has the Employee id as 1. 3. Use the$set operator to update the values
4. Choose the Field Name(s) that needs to be updatedand enter the new values accordingly –
Employee_Name =”Nandan Kumar”
Emp_ID = 21
db.Employees.update({ Emp_ID : 1},{$set :{"Employee_Name" : "Nandan Kumar"," Emp_ID" : 21}}) ## MongoDB save() Method The db.collection.save() method is used to update an existing document or insert a new document Syntax: db.collection.save() db.Employees.save( {Emp_ID : 21000 , Employee_Name : "Anshu", Salary:20000 } ); WriteResult({“ nInserted" : 1 }) The save() method returns a WriteResult object which contains the status of the insert or update operation. During the insert, the shell will create the _id field with a unique ObjectId value, as verified by the inserted document: db.Employees.find(); {"_id" : ObjectId("5da78973835b2f1c75347a83"),"Emp_ID" : 21000 , "Employee_Name" : "Anshu", "Salary":20000 } In the below example, save() method performs an insert since the document passed to the method does not contain the _id field so it creates a new document . Note If the document doesn’t contain an _id field, then the save() method calls the insert() method. db.Employees.save({_id:2400, Emp_ID : 21000 , Employee_Name : "Anshu", Salary:20000 } ); WriteResult({"nMatched": 0, "nUpserted: 1, "nModified":0,”_id”:2400}) The save() method performs an update with upsert: true since the document contains an _id field: db.Employees.save({_id:2400, Emp_ID : 21000 , Employee_Name : "Anshu", Salary:20000 } ); WriteResult({"nMatched": 1, "nUpserted: 1, "nModified":0 }) Note - If the document already contains an _id field, then the save() method is equivalent to an update with the upsert option set to true and the query predicate on the _id field. Updating Single and Multiple Values in MongoDB documents by using methods -updateOne, updateManywith examples : ## MongoDB updateOne() method This method updates a single document within a collection matching the filter or condition. Syntax The syntax of updateOne() method is − db.collection.updateOne(<filter>, <update>)  Example > db.Employees.updateOne( {First_Name: 'Nandan'}, {$set: { Age: '30',e_mail: 'nandan@gmail.com'}}
)
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 0 }

## MongoDB updateMany() method

The updateMany() method updates all the documents within a collection based on the filter or condition .

Syntax :

The syntax of updateMany() method is −

db.collection.updateMany(<filter>, <update>)

Example

>db.Employees.updateMany(
{Age:{ $gt:"25"}}, {$set:{Age:'12'}}
)
{"acknowledged":true,"matchedCount":2,"modifiedCount":2}

Using the find command, you can retrieve the contents of the documents:

> db.Employees.find()
{ "_id" : ObjectId("6fd6636870fb13eec3963bf5"), "First_Name" : "Nandan", "Last_Name" : "Kumar", "Age" : "12", "e_mail" : "nandan@gmail.com", "phone" : "8000012345
{ "_id" : ObjectId("6fd6636870fb13eec3963bf6"), "First_Name" : "Chris", "Last_Name" : "Goel", "Age" : "12", "e_mail" : "chris@gmail.com", "phone" : "8000054321" }
{ "_id" : ObjectId("6fd6636870fb13eec3963bf7"), "First_Name" : "Praveen", "Last_Name" : "Sharma", "Age" : "21", "e_mail" : "praveen@gmail.com", "phone" : "9000011111" }

## What If the update operation doesn’t match documents in collection?

If the update operation doesn't match any documents in the collection, it can automatically insert a new document into the collection which matches the update query by setting the upsert option as true.

db.Employees.update(
{type:"FullTime"},
{$set:{salary:20000}}, {upsert : true} ) WriteResult ({"nMatched": 0, "nUpserted: 1, "nModified":1 }) You can also see the upsert getting reflected in the Write Result of the above operation. upsert operation in MongoDB is used to save documents into collection . If the document matches query criteria, then it will perform an update operation or else it will insert a new document into the collection. ## Difference between db.collection.update() , db.collection.update One() and db.collection.update Many() The difference is that update() by default, modifies only one document based on the specified filter. However, the user can modify all the documents by adding the modifier {multi: true} . This command works as both updateOne and updateMany command. db.Employees.update ( { "joinYear ": "2020" }, {$set: { "bonusEligiblity": "False" },
}
)

Here, it will update only first document which matches the condition.

db.Employees.update (
{ "joinYear ": "2020" },
{
$set: { "bonusEligiblity": "False" }, }, { multi: true } // Additional Parameter ) Here, by adding the parameter – multi: true it works as updateMany() and updates all the documents matching the condition . db.collection.updateOne() --> method to update only one document in a collection. db.Employees.update ( { "joinYear ": "2020" }, {$set: { "bonusEligiblity": "False" }, // Here multiple parameters can also be updated
}
)

This update commands use the joinDate =2020 as a filter (match the query) in the collection “Employees”. $set operator (called as update operator) updates the value of the bonusEligiblity to False. You can also update multiple parameters but they need to be separated by a comma (,). E.g. $set: { "bonusEligiblity": "False" , “emp_status : ”New”},

db.collection.updateMany() --> method to update multiple document in a collection matching the specified condition

db.Employees.updateMany(
{ "joinYear": "2020" },
{
$set: { "bonusEligiblity": "False" }, } ) Here, ALL the documents having joinYear =2020 get updated to bonus Eligiblity= “False” ## What If the update operation doesn’t match documents in collection? If the update operation doesn't match any documents in the collection, it can automatically insert a new document into the collection which matches the update query by setting the upsert option as true. db.Employees.update( {type:"FullTime"}, {$set:{salary:20000}},
{upsert : true}
)

WriteResult({"nMatched": 0,  "nUpserted: 1, "nModified":1 })

You can also see the upsert getting reflected in the WriteResult of the above operation.

upsert operation in MongoDB is used to save documents into collection.

If the document matches query criteria then it will perform an update operation or else it will insert a new document into the collection.
upsert  also partially updates an object in MongoDB so that the new object will overlay or merge with the existing one.

In brief, upsert is also used to update a document with the contents of another document, but only updates the fields that are absent and completely ignore the fields that are already set.

Conclusion

To summarize, MongoDB has methods: update() and save() which are used to update documents into a collection. The update() method updates the values in the existing document while the save() method is used to insert a new document or update an existing document if it already contains an _id field The parameters in the document.update() method is a condition for which document needs to be updated, and the next is the update operation which needs to be performed.

db.collection.update (query, update, options)

In this article, we have gone over the update() method, save () method, updateOne() method and updateMany() method with examples for each. We have also explored the upsert function.

Hope this has been useful. ThMongoDB course will get you familiar with the popular NoSQL database and arm you with the essential skills to start using Mongo to power your software application. Happy coding!

Your one-stop-shop for MongoDB is just a click away. Access our live online training and find easy solutions to all your queries here.

### Nandan Kumar

Author

QA Automation Architect having 12+ Years of experience in UI , Backend and Database testing ( Selenium, Cucumber, Gherkins, Protractor, TestNG) having strong Python/Java Coding skills. Strong experience in Devops/QAops , MongoDB and Certified AWS Solution Architect.

Strong Problem solver having worked on multiple domains: Media and TV/Video Streaming, Investment Banking, E-Commerce/Payments and Cloud Security /Networking/SaaS/IaaS/PaaS.

## Handling React Events - A Detailed Guide

5355
Handling React Events - A Detailed Guide

Event handling essentially allows the user to inte... Read More

## MongoDB Query Document Using Find() With Example

MongoDB's find() method selects documents from a collection or view and returns a cursor to those documents. There are two parameters in this formula: query and projection.Query – This is an optional parameter that specifies the criteria for selection. In simple terms, a query is what you want to search for within a collection.Projection – This is an optional parameter that specifies what should be returned if the query criteria are satisfied. In simple terms, it is a type of decision-making that is based on a set of criteria.MongoDB's Flexible SchemaA NoSQL database, which stands for "not only SQL," is a way of storing and retrieving data that is different from relational databases' traditional table structures (RDBMS).When storing large amounts of unstructured data with changing schemas, NoSQL databases are indeed a better option than RDBMS. Horizontal scaling properties of NoSQL databases allow them to store and process large amounts of data.These are intended for storing, retrieving, and managing document-oriented data, which is frequently stored in JSON format (JavaScript Object Notation). Document databases, unlike RDBMSs, have a flexible schema that is defined by the contents of the documents.MongoDB is one of the most widely used open-source NoSQL document databases. MongoDB is known as a 'schemaless' database because it does not impose a specific structure on documents in a collection.MongoDB is compatible with a number of popular programming languages. It also offers a high level of operational flexibility because it scales well horizontally, allowing data to be spread or 'sharded' across multiple commodity servers with the ability to add more servers as needed. MongoDB can be run on a variety of platforms, including developer laptops, private clouds, and public clouds.Querying documents using find()MongoDB queries are used to retrieve or fetch data from a MongoDB database. When running a query, you can use criteria or conditions to retrieve specific data from the database.The function db.collection is provided by MongoDB. find() is a function that retrieves documents from a MongoDB database.In MongoDB, the find method is used to retrieve a specific document from the MongoDB collection. In Mongo DB, there are a total of six methods for retrieving specific records.find()findAndModify()findOne()findOneAndDelete()findOneAndReplace()findOneAndUpdate()Syntax:find(query, projection)We can fetch a specific record using the Find method, which has two parameters. If these two parameters are omitted, the find method will return all of the documents in the MongoDB collection.Example:Consider an example of employees with the database of employee_id and employee_name and we will fetch the documents using find() method.First, create a database with the name “employees” with the following code:use employeesNow, create a collection “employee” with:db.createCollection("employee")In the next step we will insert the documents in the database:db.employee.insert([{employee_id: 101, employee_name: "Ishan"}, {employee_id: 102, employee_name: "Bhavesh"}, {employee_id: 103, employee_name: "Madan"}])Find all Documents:To get all the records in a collection, we need to use the find method with an empty parameter. In other words, when we need all the records, we will not use any parameters.db.employee.find()Output in Mongo ShellThe pretty() method can be used to display the results in a formatted manner.Syntax:db.COLLECTION_NAME.find().pretty()Let’s check our documents with pretty() method:Query FiltersWe will see examples of query operations using the db.collection.find() method in mongosh.We will use the employee collection in the employees database.db.employee.insert([{employee_id: 101, employee_name: "Ishan", age: 21, email_id: "ishanjain@gmail.com"}, {employee_id: 102, employee_name: "Bhavesh", age: 22, email_id: "bhaveshg@gmail.com"}, {employee_id: 103, employee_name: "Madan", age: 23, email_id: "madan@gmail.com"}])As we have seen earlier that to select all the documents in the database we pass an empty document as the query filter parameter to the find method.db.employee.find().pretty()Find the first document in a collection:db.employee.findOne()Find a document by ID:db.employee.findOne({_id : ObjectId("61d1ae0b56b92c20b423a5a7")})Find Documents that Match Query Criteriadb.employee.find({“age”: “22”})db.employee.find({"employee_name": "Madan"}).pretty()Sort Results by a Field:db.employee.find().sort({age: 1}).pretty()order by age, in ascending orderdb.employee.find().sort({age: -1}).pretty()order by age, in descending orderAND Conditions:A compound query can specify conditions for multiple fields in the documents in a collection. A logical AND conjunction connects the clauses of a compound query indirectly, allowing the query to select all documents in the collection that meet the specified conditions.In the following example, we will consider all the documents in the employee collection where employee_id equals 101 and age equals 21.db.employee.find({"employee_id": 101, "age": "21" }).pretty()Querying nested fieldsThe embedded or nested document feature in MongoDB is a useful feature. Embedded documents, also known as nested documents, are documents that contain other documents.You can simply embed a document inside another document in MongoDB. Documents are defined in the mongo shell using curly braces (), and field-value pairs are contained within these curly braces.Using curly braces, we can now embed or set another document inside these fields, which can include field-value pairs or another sub-document.Syntax:{ field: { field1: value1, field2: value2 } }Example:We have a database “nested” and in this database we have collection “nesteddoc”.The following documents will insert into the nesteddoc collection.db.nesteddoc.insertMany([ { "_id" : 1, "dept" : "A", "item" : { "sku" : "101", "color" : "red" }, "sizes" : [ "S", "M" ] }, { "_id" : 2, "dept" : "A", "item" : { "sku" : "102", "color" : "blue" }, "sizes" : [ "M", "L" ] }, { "_id" : 3, "dept" : "B", "item" : { "sku" : "103", "color" : "blue" }, "sizes" : "S" }, { "_id" : 4, "dept" : "A", "item" : { "sku" : "104", "color" : "black" }, "sizes" : [ "S" ] } ])Place the documents in the collection now. Also, take a look at the results:As a result, the nesteddoc collection contains four documents, each of which contains nested documents. The find() method can be used to access the collection's documents.db.nesteddoc.find()Specify Equality Condition:In this example, we will select the document from the nesteddoc query where dept equals “A”.db.nesteddoc.find({dept: "A"})Querying ArraysUse the query document {: } to specify an equality condition on an array, where is the exact array to match, including the order of the elements.The following query looks for all documents where the field tags value is an array with exactly two elements, "S" and "M," in the order specified:db.nesteddoc.find( { sizes: ["S", "M"] } )Use the $all operator to find an array that contains both the elements "S" and "M," regardless of order or other elements in the array:db.nested.find( { sizes: {$all: ["S", "M"] } } )Query an Array for an Element:The following example queries for all documents where size is an array that contains the string “S” as one of its elements:db.nesteddoc.find( { sizes: "S" } )Filter conditionsTo discuss the filter conditions, we will consider a situation that elaborates this. We will start by creating a collection with the name “products” and then add the documents to it.db.products.insertMany([ { _id: 1, item: { name: "ab", code: "123" }, qty: 15, tags: [ "A", "B", "C" ] }, { _id: 2, item: { name: "cd", code: "123" }, qty: 20, tags: [ "B" ] }, { _id: 3, item: { name: "ij", code: "456" }, qty: 25, tags: [ "A", "B" ] }, { _id: 4, item: { name: "xy", code: "456" }, qty: 30, tags: [ "B", "A" ] }, { _id: 5, item: { name: "mn", code: "000" }, qty: 20, tags: [ [ "A", "B" ], "C" ] }])To check the documents, use db.products.find():$gt$gt selects documents with a field value greater than (or equal to) the specified value.db.products.find( { qty: { $gt: “20” } } )$gte:$gte finds documents in which a field's value is greater than or equal to (i.e. >=) a specified value (e.g. value.)db.products.find( { qty: {$gte: 20 } } )$lt:$lt selects documents whose field value is less than (or equal to) the specified value.db.products.find( { qty: { $lt: 25 } } )$lte:$lte selects documents in which the field's value is less than or equal to (i.e. =) the specified value.db.products.find( { qty: {$lte: 20 } } )Query an Array by Array Length:To find arrays with a specific number of elements, use the $size operator. For example, the following selects documents with two elements in the array.db.products.find( { "tags": {$size: 2} } )ProjectionIn MongoDB, projection refers to selecting only the data that is required rather than the entire document's data. If a document has five fields and you only want to show three of them, select only three of them.The find() method in MongoDB accepts a second optional parameter, which is a list of fields to retrieve, as explained in MongoDB Query Document. When you use the find() method in MongoDB, it displays all of a document's fields. To prevent this, create a list of fields with the values 1 or 0. The value 1 indicates that the field should be visible, while 0 indicates that it should be hidden.Syntax:db.COLLECTION_NAME.find({},{KEY:1})Example:We will consider the previous example of products collection. Run the below command on mongoshell to learn how projection works:db.products.find({},{"tags":1, _id:0})Keep in mind that the _id field is always displayed while executing the find() method; if you do not want this field to be displayed, set it to 0.Optimized FindingsTo retrieve a document from a MongoDB collection, use the Find method.Using the Find method, we can retrieve specific documents as well as the fields that we require. Other find methods can also be used to retrieve specific documents based on our needs.By inserting array elements into the query, we can retrieve specific elements or documents. To retrieve data for array elements from the collection in MongoDB, we can use multiple query operators.
6495
MongoDB Query Document Using Find() With Example

MongoDB's find() method selects documents from a c... Read More

## Implementing MongoDb Map Reduce using Aggregation

Algorithms and applications in today's data-driven market collect data about people, processes, systems, and organisations 24 hours a day, seven days a week, resulting in massive amounts of data. The problem is figuring out how to process this massive amount of data efficiently without sacrificing valuable insights.What is Map Reduce? The MapReduce programming model comes to the rescue here. MapReduce, which was first used by Google to analyse its search results, has grown in popularity due to its ability to split and process terabytes of data in parallel, generating results faster. A (Key,value) pair is the basic unit of information in MapReduce. Before feeding the data to the MapReduce model, all types of structured and unstructured data must be translated to this basic unit. The MapReduce model, as the name implies, consists of two distinct routines: the Map-function and the Reduce-function.  MapReduce is a framework for handling parallelizable problems across huge files using a huge number of devices (nodes), which are collectively referred to as a cluster (if all nodes are on the same local network and use similar hardware) or a grid (if the nodes are shared across geographically and administratively distributed systems, and use more heterogeneous hardware).  When data stored in a filesystem (unstructured) or a database(structured) is processed, MapReduce can take advantage of data's locality, processing it close to where it's stored to reduce communication costs. Typically, a MapReduce framework (or system) consists of three operations: Map: Each worker node applies the map function to local data and saves the result to a temporary storage. Only one copy of the redundant input data is processed by a master node. Shuffle: worker nodes redistribute data based on output keys (produced by the map function), ensuring that all data associated with a single key is stored on the same worker node. Reduce: each group of output data is now processed in parallel by worker nodes, per key. This article will walk you through the Map-Reduce model's functionality step by step. Map Reduce in MongoDB The map-reduce operation has been deprecated since MongoDB 5.0. An aggregation pipeline outperforms a map-reduce operation in terms of performance and usability. Aggregation pipeline operators like $group,$merge, and others can be used to rewrite map-reduce operations. Starting with version 4.4, MongoDB provides the $accumulator and$function aggregation operators for map-reduce operations that require custom functionality. In JavaScript, use these operators to create custom aggregation expressions. The map and reduce functions are the two main functions here. As a result, the data is independently mapped and reduced in different spaces before being combined in the function and saved to the specified new collection. This mapReduce() function was designed to work with large data sets only. You can perform aggregation operations like max and avg on data using Map Reduce, which is similar to groupBy in SQL. It works independently and in parallel on data. Implementing Map Reduce with Mongosh (MongoDB Shell)  The db.collection.mapReduce() method in mongosh is a wrapper for the mapReduce command. The examples that follow make use of the db.collection.mapReduce(). Example: Create a collection ‘orders’ with these documents: db.orders.insertMany([     { _id: 1, cust_id: "Ishan Jain", ord_date: new Date("2021-11-01"), price: 25, items: [ { sku: "oranges", qty: 5, price: 2.5 }, { sku: "apples", qty: 5, price: 2.5 } ], status: "A" },     { _id: 2, cust_id: "Ishan Jain", ord_date: new Date("2021-11-08"), price: 70, items: [ { sku: "oranges", qty: 8, price: 2.5 }, { sku: "chocolates", qty: 5, price: 10 } ], status: "A" },     { _id: 3, cust_id: "Bhavesh Galav", ord_date: new Date("2021-11-08"), price: 50, items: [ { sku: "oranges", qty: 10, price: 2.5 }, { sku: "pears", qty: 10, price: 2.5 } ], status: "A" },     { _id: 4, cust_id: "Bhavesh Galav", ord_date: new Date("2021-11-18"), price: 25, items: [ { sku: "oranges", qty: 10, price: 2.5 } ], status: "A" },     { _id: 5, cust_id: "Bhavesh Galav", ord_date: new Date("2021-11-19"), price: 50, items: [ { sku: "chocolates", qty: 5, price: 10 } ], status: "A"},     { _id: 6, cust_id: "Madan Parmar", ord_date: new Date("2021-11-19"), price: 35, items: [ { sku: "carrots", qty: 10, price: 1.0 }, { sku: "apples", qty: 10, price: 2.5 } ], status: "A" },     { _id: 7, cust_id: "Madan Parmar", ord_date: new Date("2021-11-20"), price: 25, items: [ { sku: "oranges", qty: 10, price: 2.5 } ], status: "A" },     { _id: 8, cust_id: "Abhresh", ord_date: new Date("2021-11-20"), price: 75, items: [ { sku: "chocolates", qty: 5, price: 10 }, { sku: "apples", qty: 10, price: 2.5 } ], status: "A" },     { _id: 9, cust_id: "Abhresh", ord_date: new Date("2021-11-20"), price: 55, items: [ { sku: "carrots", qty: 5, price: 1.0 }, { sku: "apples", qty: 10, price: 2.5 }, { sku: "oranges", qty: 10, price: 2.5 } ], status: "A" },     { _id: 10, cust_id: "Abhresh", ord_date: new Date("2021-11-23"), price: 25, items: [ { sku: "oranges", qty: 10, price: 2.5 } ], status: "A" }  ]) Apply a map-reduce operation to the orders collection to group them by cust_id, then add the prices for each cust_id: To process each input document, define the map function: this refers the document that the map-reduce operation is processing in the function. For each document, the function maps the price to the cust_id and outputs the cust_id and price. var mapFunction1 = function() {emit(this.cust_id, this.price);}; With the two arguments keyCustId and valuesPrices, define the corresponding reduce function: The elements of the valuesPrices array are the price values emitted by the map function, grouped by keyCustId. The valuesPrice array is reduced to the sum of its elements by this function. var reduceFunction1 = function(keyCustId, valuesPrices) {return Array.sum(valuesPrices);};Apply the mapFunction1 map function and the reduceFunction1 reduce function to all documents in the orders collection: db.orders.mapReduce(mapFunction1,reduceFunction1,{ out: "map_reduce_example" }) The results of this operation are saved in the map_reduce_example collection. If the map_reduce_example collection already exists, the operation will overwrite its contents with the map-reduce operation's results. Check the map_reduce_example collection to verify: db.map_reduce_example.find().sort( { _id: 1 } ) Aggregation Alternative:You can rewrite the map-reduce operation without defining custom functions by using the available aggregation pipeline operators: db.orders.aggregate([{$group: { _id:"$cust_id",value:{$sum: "$price" } } },{ \$out: "agg_alternative_1" }]) Check the agg_alternative_1 collection to verify: db.agg_alternative_1.find().sort( { _id: 1 } )Implementing Map Reduce with Java Consider the collection car and insert the following documents in it. db.car.insert( [ {car_id:"c1",name:"Audi",color:"Black",cno:"H110",mfdcountry:"Germany",speed:72,price:11.25}, {car_id:"c2",name:"Polo",color:"White",cno:"H111",mfdcountry:"Japan",speed:65,price:8.5}, {car_id:"c3",name:"Alto",color:"Silver",cno:"H112",mfdcountry:"India",speed:53,price:4.5}, {car_id:"c4",name:"Santro",color:"Grey",cno:"H113",mfdcountry:"Sweden",speed:89,price:3.5} , {car_id:"c5",name:"Zen",color:"Blue",cno:"H114",mfdcountry:"Denmark",speed:94,price:6.5} ] ) You will get an output like this:  Let's now write the map reduce function on a collection of cars, grouping them by speed and classifying them as overspeed cars.  var speedmap = function (){  var criteria;  if ( this.speed > 70 ) {criteria = 'overspeed';emit(criteria,this.speed);}}; Based on the speed, this function classifies the vehicle as an overspeed vehicle. The term "this" refers to the current document that requires map reduction. var avgspeed_reducemap = function(key, speed) {       var total =0;       for (var i = 0; i
7344
Implementing MongoDb Map Reduce using Aggregation

Algorithms and applications in today's data-driven... Read More