

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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 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 } ] }
- Related Questions & Answers
- Increment a property value of an element in array object with MongoDB
- MongoDB Increment value inside nested array?
- Increment MongoDB value inside a nested array
- Replace an array field value with MongoDB?
- Querying from part of object in an array with MongoDB
- Increment a value in a MongoDB nested object?
- Query on the last object of an array with MongoDB
- Retrieve only the queried element in an object array in MongoDB collection?
- Match element in array of MongoDB?
- MongoDB query to access an object in an array
- MongoDB query for Partial Object in an array
- MongoDB query to insert an array element with a condition?
- Pull an element in sub of sub-array in MongoDB?
- Display only an element found in an array in MongoDB?
- MongoDB query to replace value in an array?
Advertisements