- 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 use arrays as filters by querying subdocuments in MongoDB?
For this, use $setIsSubset in MongoDB. Let us create a collection with documents −
> db.demo407.insertOne( ... { ... Name:"Chris", ... "details" : [ ... { ... id:100 ... }, ... { ... id:110 ... }, ... { ... id:130 ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e70dffe15dc524f70227677") }
Display all documents from a collection with the help of find() method −
> db.demo407.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e70dffe15dc524f70227677"), "Name" : "Chris", "details" : [ { "id" : 100 }, { "id" : 110 }, { "id" : 130 } ]
Following is the query to use arrays as filters by querying subdocuments −
> db.demo407.aggregate([ ... {$match: { }}, ... {$project: { ... "details": { ... $filter: { ... input: "$details", ... as: "output", ... cond: { $setIsSubset: [["$$output.id"],[100, 130]] } ... } ... } ... }}])
This will produce the following output −
{ "_id" : ObjectId("5e70dffe15dc524f70227677"), "details" : [ { "id"
Advertisements