 
  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 field in MongoDB document which is embedded?
Let’s say, here we are incrementing StudentScores for MongoDB which is inside StudentDetails −
... "StudentScores": { ...    "StudentMathScore": 90, ...    "StudentMongoDBScore": 78 ... } Let us first create a collection with documents −
> db.embeddedValueIncrementDemo.insertOne( ...    { ...       "StudentDetails": { ...          "StudentScores": { ...             "StudentMathScore": 90, ...             "StudentMongoDBScore": 78 ...          } ...       } ...    } ... ); {    "acknowledged" : true,    "insertedId" : ObjectId("5cd2b670345990cee87fd896") } Following is the query to display all documents from a collection with the help of find() method −
> db.embeddedValueIncrementDemo.find().pretty();
This will produce the following output −
{    "_id" : ObjectId("5cd2b670345990cee87fd896"),    "StudentDetails" : {       "StudentScores" : {          "StudentMathScore" : 90,          "StudentMongoDBScore" : 78       }    } } Following is the query to increment embedded value. Here, we are incrementing StudentMongoDBScore −
> db.embeddedValueIncrementDemo.update({ _id: new ObjectId("5cd2b670345990cee87fd896") }, { $inc: { "StudentDetails.StudentScores.StudentMongoDBScore": 20 } }, { upsert: true, safe: true }, null); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) Let us check all the documents once again −
> db.embeddedValueIncrementDemo.find().pretty();
This will produce the following output −
{    "_id" : ObjectId("5cd2b670345990cee87fd896"),    "StudentDetails" : {       "StudentScores" : {          "StudentMathScore" : 90,          "StudentMongoDBScore" : 98       }    } }Advertisements
 