$filter (aggregation)

在本页面

Definition

根据指定条件选择要返回的数组的子集。返回仅包含与条件匹配的那些元素的数组。返回的元素按原始 Sequences。

$filter具有以下语法:

{ $filter: { input: <array>, as: <string>, cond: <expression> } }
Field Specification
input 解析为数组的expression
as 可选的。 variable的名称,代表input数组的每个单独元素。如果未指定名称,则变量名称默认为this
cond expression解析为一个布尔值,该布尔值用于确定是否应在输出数组中包含一个元素。该表达式使用as中指定的变量名称分别引用input数组的每个元素。

有关表达式的更多信息,请参见Expressions

Behavior

Example Results
{

$filter: {
input: [ 1,“ a”,2,null,3.1,NumberLong(4),“ 5”],
as: "num",
cond:{$和:[
{ $gte: [ "$$num", NumberLong("-9223372036854775807")] },
{ $lte: [ "$$num", NumberLong("9223372036854775807")] }
] }
}
}
[ 1, 2, 3.1, NumberLong(4) ]

Example

集合sales具有以下文档:

{
   _id: 0,
   items: [
     { item_id: 43, quantity: 2, price: 10 },
     { item_id: 2, quantity: 1, price: 240 }
   ]
}
{
   _id: 1,
   items: [
     { item_id: 23, quantity: 3, price: 110 },
     { item_id: 103, quantity: 4, price: 5 },
     { item_id: 38, quantity: 1, price: 300 }
   ]
}
{
    _id: 2,
    items: [
       { item_id: 4, quantity: 1, price: 23 }
    ]
}

下面的示例过滤items数组以仅包括price大于或等于100的文档:

db.sales.aggregate([
   {
      $project: {
         items: {
            $filter: {
               input: "$items",
               as: "item",
               cond: { $gte: [ "$$item.price", 100 ] }
            }
         }
      }
   }
])

该操作产生以下结果:

{
   "_id" : 0,
   "items" : [
      { "item_id" : 2, "quantity" : 1, "price" : 240 }
   ]
}
{
   "_id" : 1,
   "items" : [
      { "item_id" : 23, "quantity" : 3, "price" : 110 },
      { "item_id" : 38, "quantity" : 1, "price" : 300 }
   ]
}
{ "_id" : 2, "items" : [ ] }
首页