- 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
MongoDB query to update each field of documents in collection with a formula?
To update each field of documents in collection with a formula, use MongoDB update(). Let us create a collection with documents −
> db.demo749.insertOne({"details":[{"id":1,a:10},{"id":2,a:5},{"id":3,a:20}]}); { "acknowledged" : true, "insertedId" : ObjectId("5eae6fb0a930c785c834e565") }
Display all documents from a collection with the help of find() method −
> db.demo749.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5eae6fb0a930c785c834e565"), "details" : [ { "id" : 1, "a" : 10 }, { "id" : 2, "a" : 5 }, { "id" : 3, "a" : 20 } ] }
Following is the query to update each field of documents in collection with a formula −
> db.demo749.update( ... { ... ... }, ... { ... $mul: { "details.$[].a": 2/5} ... }, ... { multi:true} ... ) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo749.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5eae6fb0a930c785c834e565"), "details" : [ { "id" : 1, "a" : 4 }, { "id" : 2, "a" : 2 }, { "id" : 3, "a" : 8 } ] }
- Related Articles
- How to update many documents with one query in MongoDB?
- MongoDB query to update array with another field?
- How to Update multiple documents in a MongoDB collection using Java?
- How to update or modify the existing documents of a collection in MongoDB?
- MongoDB query to update a specific document from a collection
- How to update a single field in a capped collection in MongoDB?
- Get the maximum mark records from a collection with documents in MongoDB query
- MongoDB query to collectively match intersection of documents against a field
- MongoDB query to update all documents matching specific IDs
- How to add a new field to all the documents in a MongoDB collection
- Find all duplicate documents in a MongoDB collection by a key field?
- MongoDB query to add up the values of a specific field in documents
- Update salary field value with 10 percent of each employee in MongoDB
- Display only a single field from all the documents in a MongoDB collection
- Finding documents in MongoDB collection where a field is equal to given integer value?

Advertisements