- 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 find value in array with multiple criteria (range)
To find value in an array within a range, use $gt and $lt. Let us create a collection with documents −
> db.demo341.insertOne({ ... "Name": "Chris", ... "productDetails" : [ ... { ... "ProductPrice" : { ... "Price" : 800 ... } ... }, ... { ... "ProductPrice" : { ... "Price" : 400 ... } ... }, ... { ... "ProductPrice" : { ... "Price" : 300 ... } ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e53ed5cf8647eb59e5620a7") } > db.demo341.insertOne({ ... "Name": "Chris", ... "productDetails" : [ ... { ... "ProductPrice" : { ... "Price" : 1000 ... } ... }, ... { ... "ProductPrice" : { ... "Price" : 1200 ... } ... }, ... { ... "ProductPrice" : { ... "Price" : 1300 ... } ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e53edc1f8647eb59e5620a8") }
Display all documents from a collection with the help of find() method −
> db.demo341.find();
This will produce the following output −
{ "_id" : ObjectId("5e53ed5cf8647eb59e5620a7"), "Name" : "Chris", "productDetails" : [ { "ProductPrice" : { "Price" : 800 } }, { "ProductPrice" : { "Price" : 400 } }, { "ProductPrice" : { "Price" : 300 } } ] } { "_id" : ObjectId("5e53edc1f8647eb59e5620a8"), "Name" : "Chris", "productDetails" : [ { "ProductPrice" : { "Price" : 1000 } }, { "ProductPrice" : { "Price" : 1200 } }, { "ProductPrice" : { "Price" : 1300 } } ] }
Following is the query to find value in the array with multiple criteria −
> db.demo341.aggregate([ ... { "$match": { ... "productDetails": { ... "$elemMatch": { ... "ProductPrice.Price": { ... "$gt": 600, ... "$lt": 900 ... } ... } ... } ... }} ... ]).pretty();
This will produce the following output −
{ "_id" : ObjectId("5e53ed5cf8647eb59e5620a7"), "Name" : "Chris", "productDetails" : [ { "ProductPrice" : { "Price" : 800 } }, { "ProductPrice" : { "Price" : 400 } }, { "ProductPrice" : { "Price" : 300 } } ] }
Advertisements