- Trending Categories
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
Update a single list item of a Mongo DB document and increment it by 1
For this, use positional operator($). To increment a field value by 1, use $inc operator. Let us create a collection with documents −
>db.demo39.insertOne({"ProductDetails":[{"ProductName":"Product-1","ProductPrice":349}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e176d54cfb11e5c34d898df") } >db.demo39.insertOne({"ProductDetails":[{"ProductName":"Product-2","ProductPrice":998}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e176d61cfb11e5c34d898e0") } >db.demo39.insertOne({"ProductDetails":[{"ProductName":"Product-3","ProductPrice":145}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e176d6acfb11e5c34d898e1") }
Display all documents from a collection with the help of find() method −
> db.demo39.find();
This will produce the following output −
{ "_id" : ObjectId("5e176d54cfb11e5c34d898df"), "ProductDetails" : [ { "ProductName" : "Product-1", "ProductPrice" : 349 } ] } { "_id" : ObjectId("5e176d61cfb11e5c34d898e0"), "ProductDetails" : [ { "ProductName" : "Product-2", "ProductPrice" : 998 } ] } { "_id" : ObjectId("5e176d6acfb11e5c34d898e1"), "ProductDetails" : [ { "ProductName" : "Product-3", "ProductPrice" : 145 } ] }
Following is the query to update a single list item of a MongoDB document −
> db.demo39.update({"_id" : ObjectId("5e176d61cfb11e5c34d898e0"),'ProductDetails.ProductName':"Product-2"},{$inc: {'ProductDetails.$.ProductPrice': 1}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo39.find();
This will produce the following output −
{ "_id" : ObjectId("5e176d54cfb11e5c34d898df"), "ProductDetails" : [ { "ProductName" : "Product-1", "ProductPrice" : 349 } ] } { "_id" : ObjectId("5e176d61cfb11e5c34d898e0"), "ProductDetails" : [ { "ProductName" : "Product-2", "ProductPrice" : 999 } ] } { "_id" : ObjectId("5e176d6acfb11e5c34d898e1"), "ProductDetails" : [ { "ProductName" : "Product-3", "ProductPrice" : 145 } ] }
Advertisements