![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
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 filter array in subdocument with MongoDB?
You can use aggregate and unwind the array list before applying match. To understand the above concept, let us create a collection with documents. The query to create a collection with document is as follows:
> db.filterArray.insertOne( { "L": [{ "N":1 }, { "N":2 } , { "N":3 }, { "N":4 }, { "N":5 } ]});
The following is visible after running the above query:
{ "acknowledged" : true, "insertedId" : ObjectId("5c6d63f2734e98fc0a434aeb") }
Display document from a collection with the help of find() method. The query is as follows:
> db.filterArray.find().pretty();
The following is the output:
{ "_id" : ObjectId("5c6d63f2734e98fc0a434aeb"), "L" : [ { "N" : 1 }, { "N" : 2 }, { "N" : 3 }, { "N" : 4 }, { "N" : 5 } ] }
Here is the query to filter array in subdocument with MongoDB. We have used $gt to get the fields greater than 3:
> db.filterArray.aggregate({ $match:{_id:ObjectId("5c6d63f2734e98fc0a434aeb")}}, { $unwind:'$L'}, {$match:{'L.N':{$gt:3}}}, {$group:{_id:'$_id',subDocument:{$push:'$L.N'}}}).pretty();
The following is the output:
{ "_id" : ObjectId("5c6d63f2734e98fc0a434aeb"), "subDocument" : [ 4, 5 ] }
Advertisements