 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
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
 