MongoDB Tutorial Beginners

Filtering Data in MongoDB - The $filter Operator


Introduction to Filtering Data in MongoDB

Filtering data is a common operation when working with MongoDB. The `$filter` operator is a powerful tool that allows you to select and retrieve specific elements from an array within your documents. In this guide, we'll explore how to use the `$filter` operator in MongoDB with sample code.

The $filter Operator

The `$filter` operator is used within the aggregation framework in MongoDB. It filters elements from an array based on specified conditions. The operator has the following syntax:

{
    $filter: {
        input: `arrayField`,
        as: `alias`,
        cond: `filterCondition`
    }
}
        

input: The array field you want to filter.

as: An alias for the array elements.

cond: The filtering condition that each element in the array must satisfy.

Sample Usage of $filter

Let's look at a practical example of how to use the `$filter` operator in MongoDB:

db.myCollection.aggregate([
    {
        $project: {
            filteredArray: {
                $filter: {
                    input: `$arrayField`,
                    as: `item`,
                    cond: { $gte: [`$$item.score`, 90] }
                }
            }
        }
    }
])
        

In this example, we filter the `arrayField` array, keeping only the elements where the `score` field is greater than or equal to 90. The resulting `filteredArray` contains the filtered elements.

Conclusion

The `$filter` operator in MongoDB provides a powerful way to filter and retrieve specific elements from arrays within your documents. It's a valuable tool for data manipulation and analysis, especially when working with complex and nested data structures.

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.