- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
How to increment a field in MongoDB?
To increment a field in MongoDB, you can use $inc operator. Let us first create a collection with documents −
> db.incrementDemo.insertOne({"PlayerScore":100}); { "acknowledged" : true, "insertedId" : ObjectId("5cc81cdd8f9e6ff3eb0ce44e") } > db.incrementDemo.insertOne({"PlayerScore":290}); { "acknowledged" : true, "insertedId" : ObjectId("5cc81ce28f9e6ff3eb0ce44f") } > db.incrementDemo.insertOne({"PlayerScore":560}); { "acknowledged" : true, "insertedId" : ObjectId("5cc81ce68f9e6ff3eb0ce450") }
Following is the query to display all documents from a collection with the help of find() method −
> db.incrementDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cc81cdd8f9e6ff3eb0ce44e"), "PlayerScore" : 100 } { "_id" : ObjectId("5cc81ce28f9e6ff3eb0ce44f"), "PlayerScore" : 290 } { "_id" : ObjectId("5cc81ce68f9e6ff3eb0ce450"), "PlayerScore" : 560 }
Following is the query to increment a field in MongoDB −
> db.incrementDemo.update({ _id:ObjectId("5cc81ce28f9e6ff3eb0ce44f") },{ $inc: {"PlayerScore":10 }}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
In the above query, I have incremented the value 290 with value 10 −
> db.incrementDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cc81cdd8f9e6ff3eb0ce44e"), "PlayerScore" : 100 } { "_id" : ObjectId("5cc81ce28f9e6ff3eb0ce44f"), "PlayerScore" : 300 } { "_id" : ObjectId("5cc81ce68f9e6ff3eb0ce450"), "PlayerScore" : 560 }
- Related Articles
- Increment a field in MongoDB document which is embedded?
- How to increment inside the update() function in MongoDB?
- How to make a unique field in MongoDB?
- How to insert a boolean field in MongoDB?
- How to select a single field in MongoDB?
- MySQL increment a database field by 1?
- Increment a value in a MongoDB nested object?
- How to determine whether a field exists in MongoDB?
- How to check empty field in a MongoDB collection?
- How to compare field values in MongoDB?
- How to improve querying field in MongoDB?
- How to update _id field in MongoDB?
- Increment only a single value in MongoDB document?
- Increment MongoDB value inside a nested array
- How to return only value of a field in MongoDB?

Advertisements