
- 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
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 }
- Related Questions & Answers
- MongoDB query to pull a specific value from a document
- MongoDB query (aggregation framework) to match a specific field value
- Query an array in MongoDB to fetch a specific value
- MongoDB query to determine if a specific value does not exist?
- Increment MongoDB value inside a nested array
- How to run MongoDB query to update only a specific field value?
- Increment a value in a MongoDB nested object?
- MongoDB query to remove a specific document
- MongoDB query to fetch a specific document rom documents with field value set using NumberInt()?
- How to use custom variable while updating a MongoDB document?
- MongoDB Increment value inside nested array?
- Increment only a single value in MongoDB document?
- Truncate a MySQL table and then set a custom value to auto increment
- MongoDB query to sum specific fields
- MongoDB query to group records and display a specific value with dot notation
Advertisements