- 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 to select where sum of fields is greater than a value in MongoDB?
You can use $where operator for this. Let us first create a collection with documents −
> db.sumOfFieldIsGreaterThanDemo.insertOne({"Price1":10,"Price2":50,"Price3":40}); { "acknowledged" : true, "insertedId" : ObjectId("5cdd84b8bf3115999ed511e6") } > db.sumOfFieldIsGreaterThanDemo.insertOne({"Price1":11,"Price2":1,"Price3":120}); { "acknowledged" : true, "insertedId" : ObjectId("5cdd84c6bf3115999ed511e7") } > db.sumOfFieldIsGreaterThanDemo.insertOne({"Price1":10,"Price2":9,"Price3":6}); { "acknowledged" : true, "insertedId" : ObjectId("5cdd84d2bf3115999ed511e8") }
Following is the query to display all documents from a collection with the help of find() method −
> db.sumOfFieldIsGreaterThanDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5cdd84b8bf3115999ed511e6"), "Price1" : 10, "Price2" : 50, "Price3" : 40 } { "_id" : ObjectId("5cdd84c6bf3115999ed511e7"), "Price1" : 11, "Price2" : 1, "Price3" : 120 } { "_id" : ObjectId("5cdd84d2bf3115999ed511e8"), "Price1" : 10, "Price2" : 9, "Price3" : 6 }
Following is the query to select where sum of fields is greater than a value in MongoDB −
> db.sumOfFieldIsGreaterThanDemo.find( {$where: function() { return this.Price1+this.Price2+this.Price3 > 100 }} );
This will produce the following output −
{ "_id" : ObjectId("5cdd84c6bf3115999ed511e7"), "Price1" : 11, "Price2" : 1, "Price3" : 120 }
Advertisements
To Continue Learning Please Login
Login with Google