- Trending Categories
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
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 } ] }
Advertisements