- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 property value of an element in array object with MongoDB
To increment a property value of an element, use update() in MongoDB and in that, work with #$inc to increment. Let us first create a collection with documents −
> db.demo97.insertOne({ ... "Details": [ ... { ... "Name": "Chris", ... "Marks": 45 ... }, ... { ... "Name": "Bob", ... "Marks": 88 ... }y ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e2d6d24b8903cdd865577af") }
Display all documents from a collection with the help of find() method −
> db.demo97.find();
This will produce the following output −
{ "_id" : ObjectId("5e2d6d24b8903cdd865577af"), "Details" : [ { "Name" : "Chris", "Marks" : 45 }, { "Name" : "Bob", "Marks" : 88 } ] }
Following is the query to increment a property value of an element in array object −
> db.demo97.update( ... { "Details.Name": "Bob"}, ... { $inc: { "Details.$.Marks" : 10 } } ... ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo97.find();
This will produce the following output −
{ "_id" : ObjectId("5e2d6d24b8903cdd865577af"), "Details" : [ { "Name" : "Chris", "Marks" : 45 }, { "Name" : "Bob", "Marks" : 98 } ] }
Advertisements