$filter
The `$filter` operator is used to filter elements from an array based on a specified condition. This operator is useful when you need to manipulate or retrieve specific array elements within documents.
Syntax
{
$filter: {
input: "<array>",
as: "<string>",
cond: "<expression>"
}
}
Parameters
input
stringrequiredAn expression that resolves to an array.
as
stringrequiredA string that specifies the variable name for each element in the input array.
cond
stringrequiredAn expression that determines whether to include the element in the output array.
Examples
Sample Data
{
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
"promotionEvents": [
{
"discounts": [
{ "categoryName": "DJ Turntables", "discountPercentage": 18 },
{ "categoryName": "DJ Mixers", "discountPercentage": 15 }
]
}
]
}
Filter discounts above a threshold
Filter promotional discounts to only include those with discount percentage greater than 15.
Query:
db.stores.aggregate([
{ $match: { _id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5" } },
{
$project: {
name: 1,
highDiscounts: {
$filter: {
input: { $arrayElemAt: ["$promotionEvents.discounts", 0] },
as: "discount",
cond: { $gt: ["$$discount.discountPercentage", 15] }
}
}
}
}
])
Output:
[
{
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
"name": "Lakeshore Retail | DJ Equipment Stop",
"highDiscounts": [
{ "categoryName": "DJ Turntables", "discountPercentage": 18 }
]
}
]