- 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
Filter by several array elements in MongoDB?
For this, you can use $elemMatch operator. The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria. Let us first create a collection with documents −
> db.filterBySeveralElementsDemo.insertOne( "_id":100, "StudentDetails": [ { "StudentName": "John", "StudentCountryName": "US", }, { "StudentName": "Carol", "StudentCountryName": "UK" } ] } ); { "acknowledged" : true, "insertedId" : 100 } > db.filterBySeveralElementsDemo.insertOne( { "_id":101, "StudentDetails": [ { "StudentName": "Sam", "StudentCountryName": "AUS", }, { "StudentName": "Chris", "StudentCountryName": "US" } ] } ); { "acknowledged" : true, "insertedId" : 101 }
Following is the query to display all documents from a collection with the help of find() method −
> db.filterBySeveralElementsDemo.find().pretty();
This will produce the following output −
{ "_id" : 100, "StudentDetails" : [ { "StudentName" : "John", "StudentCountryName" : "US" }, { "StudentName" : "Carol", "StudentCountryName" : "UK" } ] } { "_id" : 101, "StudentDetails" : [ { "StudentName" : "Sam", "StudentCountryName" : "AUS" }, { "StudentName" : "Chris", "StudentCountryName" : "US" } ] }
Following is the query to filter by several array elements −
> db.filterBySeveralElementsDemo.find({ StudentDetails: { $elemMatch: { StudentName: 'Sam', StudentCountryName: 'AUS' }}}).pretty();
This will produce the following output −
{ "_id" : 101, "StudentDetails" : [ { "StudentName" : "Sam", "StudentCountryName" : "AUS" }, { "StudentName" : "Chris", "StudentCountryName" : "US" } ] }
Advertisements