- 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 value of an array element with array object in MongoDB
To increment the value of an array object, use $inc. Let us create a collection with documents −
>db.demo506.insertOne({"details":[{id:1,Quantity:4},{id:2,Quantity:3},{id:3,Quantity:2},{id:4,Qua ntity:7}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e882ed6987b6e0e9d18f576") }
Display all documents from a collection with the help of find() method −
> db.demo506.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e882ed6987b6e0e9d18f576"), "details" : [ { "id" : 1, "Quantity" : 4 }, { "id" : 2, "Quantity" : 3 }, { "id" : 3, "Quantity" : 2 }, { "id" : 4, "Quantity" : 7 } ] }
Following is the query to increment the value of an array element name quantity with array object −
> db.demo506.update({"details.id":2},{$inc:{"details.$.Quantity":10}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo506.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e882ed6987b6e0e9d18f576"), "details" : [ { "id" : 1, "Quantity" : 4 }, { "id" : 2, "Quantity" : 13 }, { "id" : 3, "Quantity" : 2 }, { "id" : 4, "Quantity" : 7 } ] }
Advertisements