How to filter array elements in MongoDB?


You can use $setIntersection operator along with aggregate framework to filter array elements in MongoDB. Let us first create a collection with documents −

> db.filterArrayElementsDemo.insertOne( { "Scores": [10,45,67,78,90,98,99,92] } );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2d582b64f4b851c3a13c8")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.filterArrayElementsDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cd2d582b64f4b851c3a13c8"),
   "Scores" : [
      10,
      45,
      67,
      78,
      90,
      98,
      99,
      92
   ]
}

Following is the query to filter array elements −

> db.filterArrayElementsDemo.aggregate([
...    { $match : {
...          _id: ObjectId("5cd2d582b64f4b851c3a13c8")
...    }},
...    { $project: {
...       Scores: {
...          $setIntersection: ['$Scores', [10,98,99]]
...       }
...    }}
... ]);

This will produce the following output −

{ "_id" : ObjectId("5cd2d582b64f4b851c3a13c8"), "Scores" : [ 10, 98, 99 ] }

Updated on: 30-Jul-2019

226 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements