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"
      }
   ]
}

Updated on: 30-Jul-2019

108 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements