

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 ] }
- Related Questions & Answers
- How to filter array elements in MongoDB?
- How to select a specific subdocument in MongoDB?
- Finding a specific item in subdocument with MongoDB?
- Sort by subdocument in MongoDB
- MongoDB query to find and return subdocument with criteria?
- MongoDB to sort by subdocument match?
- How to sort, select and query subdocument in MongoDB?
- Filter query on array of embedded document with MongoDB?
- How to find specific array elements in MongoDB document with query and filter with range?
- How to filter documents based on an array in MongoDB?
- Filter by several array elements in MongoDB?
- MongoDB query to remove subdocument from document?
- Display MongoDB with document and subdocument example and update
- MongoDB query on nth element (variable index) of subdocument array
- MongoDB query to filter by several array elements?
Advertisements