- 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
Querying array of Embedded Documents in MongoDB based on Range?
To query an array of embedded documents based on range, use aggregate(). Let us create a collection with documents −
> db.demo346.insertOne( ... { ... _id: 101, ... userDetails: [ ... { UserName: "Chris", Score:78}, ... { UserName: "David", Score:68}, ... { UserName: "Bob", Score:88} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 101 } > db.demo346.insertOne( ... { ... _id: 102, ... userDetails: [ ... { UserName: "Mike", Score:92}, ... { UserName: "Sam", Score:62}, ... { UserName: "Carol", Score:97} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 102 }
Display all documents from a collection with the help of find() method −
> db.demo346.find();
This will produce the following output −
{ "_id" : 101, "userDetails" : [ { "UserName" : "Chris", "Score" : 78 }, { "UserName" : "David", "Score" : 68 }, { "UserName" : "Bob", "Score" : 88 } ] } { "_id" : 102, "userDetails" : [ { "UserName" : "Mike", "Score" : 92 }, { "UserName" : "Sam", "Score" : 62 }, { "UserName" : "Carol", "Score" : 97 } ] }
Following is how to query an array of embedded documents in MongoDB based on Range −
> db.demo346.aggregate([ ... { "$match": { "$expr": { "$gte": [{ "$size": { "$ifNull": ["$userDetails", []] } }, 1] }}}, ... { "$addFields": { ... "userDetails": { ... "$filter": { ... "input": { "$ifNull": ["$userDetails", []] }, ... "cond": { ... "$and": [ ... { "$gte": ["$$this.Score", 80] }, ... { "$lte": ["$$this.Score", 99] } ... ] ... } ... } ... } ... }} ... ])
This will produce the following output −
{ "_id" : 101, "userDetails" : [ { "UserName" : "Bob", "Score" : 88 } ] } { "_id" : 102, "userDetails" : [ { "UserName" : "Mike", "Score" : 92 }, { "UserName" : "Carol", "Score" : 97 } ] }
Advertisements