本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$filter
Amazon DocumentDB 中的$filter运算符用于将筛选表达式应用于数组的每个元素,并返回一个仅包含符合指定条件的元素的数组。当您需要对文档中的数组字段执行复杂的筛选操作时,此运算符很有用。
参数
-
input: 要筛选的数组字段。 -
as:用于cond表达式中数组中每个input元素的变量名。 -
cond: 布尔表达式,用于确定是否应将给定元素包含在输出数组中。
示例(MongoDB 外壳)
以下示例演示如何使用$filter运算符来预测每个订单的客户,并创建一个新的数组字段 paidItems,其中仅包含价格大于 15 的 items 数组中的商品。从本质上讲,它会筛选每个订单的商品,仅包括价格超过15的产品。
创建示例文档
db.orders.insertMany([ { _id: 1, customer: "abc123", items: [ { name: "Product A", price: 10, qty: 2 }, { name: "Product B", price: 20, qty: 1 } ]}, { _id: 2, customer: "def456", items: [ { name: "Product C", price: 5, qty: 3 }, { name: "Product D", price: 15, qty: 4 } ]}, { _id: 3, customer: "ghi789", items: [ { name: "Product E", price: 8, qty: 3 }, { name: "Product F", price: 12, qty: 1 } ]} ]);
查询示例
db.orders.aggregate([ { $project: { customer: 1, paidItems: { $filter: { input: "$items", as: "item", cond: { $gt: ["$$item.price", 15] } } } } } ]).pretty();
输出
[
{
_id: 1,
customer: 'abc123',
paidItems: [ { name: 'Product B', price: 20, qty: 1 } ]
},
{ _id: 2, customer: 'def456', paidItems: [] },
{ _id: 3, customer: 'ghi789', paidItems: [] }
]
代码示例
要查看使用该$filter命令的代码示例,请选择要使用的语言的选项卡: