• Post author:
  • Post category:MongoDB
  • Post last modified:May 9, 2024
  • Reading time:10 mins read
You are currently viewing MongoDB $filter Operator Usage

The $filter operator in MongoDB allows us to iterate over an array field in a document and apply a filter to select only the elements that match certain conditions. In this article, we will explore the $filter operator in MongoDB to efficiently work with array elements.

Advertisements

I will use the below collection to explain this example.


# Collection
db.student.insertMany([
{
   "_id" : 1,
   "details" : [
      {"name": "Jennah", "age" : 23, "marks" : 90 }
   ],
  "assignmentMarks": [10, 6, 8] 
},
{
   "_id" : 2,
   "details" : [
      { "name": "Alice", "age" : 25, "marks" : 85 }
   ],
    "assignmentMarks": [11, 2, 5] 
},
{ "_id" : 3, "details" : [ ],  "assignmentMarks": []} ,
{
   "_id" : 4,
   "details" : [
      { "name": "Emily", "age" : 21, "marks" : 80 }
   ],
   "assignmentMarks": [10, 6, 8] 
}
])

If you want to know the method to create a collection, you can use this link.

1. Syntax of $filter operator

Let’s dive into the syntax and usage of the $filter operator in MongoDB.


# Syntax
db.collection_name.aggregate([
   {
      $project: {
  field: {
    $filter: {
      input: arrayField,
      as: variable,
      cond: criteria
    }
  }
} }
])

The field parameter, in this case, refers to the document field where the array is kept. The filtering mechanism is applied using the $filter operator.

  • input: This is the array field that you want to filter.
  • as: This is the name to assign to each element of the array while filtering.
  • cond: This is the condition that each element is evaluated against. Only elements for which the condition is true will be included in the filtered array.

2. What is $filter operator and how to use it?

MongoDB aggregation framework provides a $filter operator that allows you to filter elements in an array or embedded array within a document. This operator is typically used within the $project stage of aggregation to conditionally include or exclude elements from an array field.


# Usage of $filter operator
db.student.aggregate([
   {
      $project: {
         details: {
            $filter: {
               input: "$details",
               as: "info",
               cond: { $gt: [ "$$info.age", 21 ] }
            }
         }
      }
   }
])

The above aggregation is specified with the $filter stage. The $filter operator here filters the elements of the details array. It takes an input array, which is set to $details to reference the original details field of the document being processed. After that, the as parameter sets the variable name to info for each element in the details array. Next, the cond parameter specifies the condition that each element in the details array must satisfy to be included in the filtered array. The condition checks if the value of $$info.age is greater than 21.

Thus, the resulting output generates an array of documents that fulfill the given condition.

Filter Operator in MongoDB

2. Using the $filter operator with the Limit option

Moreover, we use the $filter operator to filter the given array along with a limit parameter to the number of filtered elements returned.


# Usage of $filter operator with the Limit option
db.student.aggregate( [
   {
      $project: {
         details: {
            $filter: {
               input: "$details",
               cond: { $gt: [ "$$result.marks", 80 ] },
               as: "result",
               limit: 1
            }
         }
      }
   }
] )

The $filter operator is passed in the above aggregation pipeline to filter the elements of the details array. It requires an input array, which is set to $details to correspond to the document’s original details field. We then called the cond parameter to specify the condition that each element in the details array must satisfy to be included in the filtered array.

In this case, the condition determines whether $$result.marks has a value greater than 80. The limit parameter is then used to limit the number of elements in the resulting filtered array. As the value set is 1, so only the first element that satisfies the condition will be included in the filtered array. 

There, the output is obtained with an array of documents, each containing a details field that includes the first element from the original details array where the marks are greater than or equal to 80.

3. Using the $filter operator with the $$this operator

When using the $filter, we can access the value of the current element being processed using the special variable $$this. This allows us to apply conditions and comparisons to the current element.


# Usage of $filter operator with the $$this operator
db.student.aggregate([
  {
    $match: { _id: { $in: [ 1, 2, 4 ] } }
  },
  {
    $project: {
        AssignmentPoints: {
          $filter: {
              input: "$assignmentMarks",
              cond: { $lt: [ "$$this", 8 ] }
          }
        }
    }
  }
])

Here, the aggregation pipeline is deployed in two stages. The first stage is $match, which filters the documents based on a condition. It matches documents where the _id field is either 1, 2, or 4. Then, the second stage is the $project, where the $filter operator is called to filter the elements of the assignmentMarks array. Further, it takes a cond parameter that specifies the condition that each element in the assignmentMarks array must satisfy to be included in the filtered array. The conditions are based on the value of the current element being processed by referencing it with the $this variable.

Hence, the output yielded as expected from the above filter query.

Filter Operator in MongoDB

4. Using the $filter operator for an empty array

In addition to the aforementioned illustrations, when using the $filter operator in MongoDB, if the input array is empty, the $filter operator will return an empty array as a result. There, we perform the $filter operator on the empty array.


# Usage of $filter operator for an empty array
db.student.aggregate([
  { 
    $match: { _id: { $in: [ 3 ] } } 
  },
  {
    $project: {
        highPoints: {
          $filter: {
              input: "$assignmentMarks",
              as: "points",
              cond: { $gt: [ "$$points", 9 ] }
          }
        }
    }
  }
])

The $filter operator is employed here to filter the elements of the assignmentMarks array. It takes the required parameters to query the filter document. Note that the condition is { $gt: [ "$$points", 9 ] }, but since there are no elements in the input array, the condition is never evaluated.

As a result, the output displayed an empty array of a document. 

Filter Operator in MongoDB

5. Conclusion

In conclusion, the $filter query operator in MongoDB provides a powerful tool for working with array elements. It allows you to perform conditional filtering on arrays within documents during the aggregation pipeline. Here, we demonstrate the structure and the usage of the $filter operator query with examples.

More details about this topic can be found here.