- 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
MongoDB query to increment a specific value using custom variable
Set a custom variable and use update() along with $inc to increment. Let us create a collection with documents −
> db.demo271.insertOne({"Marks":56}); { "acknowledged" : true, "insertedId" : ObjectId("5e4821211627c0c63e7dbabc") } > db.demo271.insertOne({"Marks":78}); { "acknowledged" : true, "insertedId" : ObjectId("5e4821241627c0c63e7dbabd") } > db.demo271.insertOne({"Marks":72}); { "acknowledged" : true, "insertedId" : ObjectId("5e48212b1627c0c63e7dbabe") }
Display all documents from a collection with the help of find() method −
> db.demo271.find();
This will produce the following output −
{ "_id" : ObjectId("5e4821211627c0c63e7dbabc"), "Marks" : 56 } { "_id" : ObjectId("5e4821241627c0c63e7dbabd"), "Marks" : 78 } { "_id" : ObjectId("5e48212b1627c0c63e7dbabe"), "Marks" : 72 }
Following is the query to increment using a custom variable −
> var incrementValue=10; > db.demo271.update( ... { Marks: 78 }, ... { $inc: { Marks:incrementValue } } ...) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo271.find();
This will produce the following output −
{ "_id" : ObjectId("5e4821211627c0c63e7dbabc"), "Marks" : 56 } { "_id" : ObjectId("5e4821241627c0c63e7dbabd"), "Marks" : 88 } { "_id" : ObjectId("5e48212b1627c0c63e7dbabe"), "Marks" : 72 }
Advertisements