 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Increment a value in a MongoDB nested object?
To increment a value in nested object, you can use $inc operator. Let us first implement the following query to create a collection with documents
>db.incrementValueDemo.insertOne({"StudentName":"Larry","StudentCountryName":"US","StudentDetails":[{"StudentSubjectName":"Math","StudentMathMarks":79}]}); {    "acknowledged" : true,    "insertedId" : ObjectId("5c986ca0330fd0aa0d2fe4a2") } Following is the query to display all documents from a collection with the help of find() method
> db.incrementValueDemo.find().pretty();
This will produce the following output
{    "_id" : ObjectId("5c986ca0330fd0aa0d2fe4a2"),    "StudentName" : "Larry",    "StudentCountryName" : "US",    "StudentDetails" : [       {          "StudentSubjectName" : "Math",          "StudentMathMarks" : 79       }    ] } Following is the query to increment a value in nested object. The marks would get incremented here
> db.incrementValueDemo.update( {"StudentDetails.StudentSubjectName":"Math"}, { $inc : {    "StudentDetails.$.StudentMathMarks" : 1 } });    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) Following is the query to check the value is incremented or not
> db.incrementValueDemo.find().pretty();
This will produce the following output
{    "_id" : ObjectId("5c986ca0330fd0aa0d2fe4a2"),    "StudentName" : "Larry",    "StudentCountryName" : "US",    "StudentDetails" : [       {          "StudentSubjectName" : "Math",          "StudentMathMarks" : 80       }    ] }Advertisements
 