- 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
How can I update and increment two fields in one command in MongoDB?
Let us first create a collection with documents −
> db.incrementDemo.insertOne({"Value1":10,"Value2":20}); { "acknowledged" : true, "insertedId" : ObjectId("5cbdaf07de8cc557214c0e15") }
Display all documents from a collection with the help of find() method. The query is as follows −
> db.incrementDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cbdaf07de8cc557214c0e15"), "Value1" : 10, "Value2" : 20 }
Following is the query to increment two fields in one command in MongoDB −
> db.incrementDemo.update({},{ $inc : { Value1 : 1, Value2 : 1 } }); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check both the fields have been incremented with value 1 or not −
> db.incrementDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cbdaf07de8cc557214c0e15"), "Value1" : 11, "Value2" : 21 }
Advertisements