
- MongoDB Tutorial
- MongoDB - Home
- MongoDB - Overview
- MongoDB - Advantages
- MongoDB - Environment
- MongoDB - Data Modeling
- MongoDB - Create Database
- MongoDB - Drop Database
- MongoDB - Create Collection
- MongoDB - Drop Collection
- MongoDB - Data Types
- MongoDB - Insert Document
- MongoDB - Query Document
- MongoDB - Update Document
- MongoDB - Delete Document
- MongoDB - Projection
- MongoDB - Limiting Records
- MongoDB - Sorting Records
- MongoDB - Indexing
- MongoDB - Aggregation
- MongoDB - Replication
- MongoDB - Sharding
- MongoDB - Create Backup
- MongoDB - Deployment
- MongoDB - Java
- MongoDB - PHP
- Advanced MongoDB
- MongoDB - Relationships
- MongoDB - Database References
- MongoDB - Covered Queries
- MongoDB - Analyzing Queries
- MongoDB - Atomic Operations
- MongoDB - Advanced Indexing
- MongoDB - Indexing Limitations
- MongoDB - ObjectId
- MongoDB - Map Reduce
- MongoDB - Text Search
- MongoDB - Regular Expression
- Working with Rockmongo
- MongoDB - GridFS
- MongoDB - Capped Collections
- Auto-Increment Sequence
- MongoDB Useful Resources
- MongoDB - Questions and Answers
- MongoDB - Quick Guide
- MongoDB - Useful Resources
- MongoDB - Discussion
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 }
- Related Articles
- How can I update child objects in MongoDB?
- MongoDB - how can I access fields in a document?
- How to increment inside the update() function in MongoDB?
- Update only specific fields in MongoDB?
- How can I update child objects in MongoDB database?
- Combine two MySQL fields and update a third one with result?
- Update two separate arrays in a document with one update call in MongoDB?
- MongoDB query to update selected fields
- Update MySQL date and increment by one Year?
- How to update record in MongoDB without replacing the existing fields?
- MongoDB query to update only certain fields?
- How to update only one property in MongoDB?
- Merge two array fields in MongoDB?
- How can we update a record in MongoDB?
- How to perform Increment in MySQL Update?

Advertisements