$filter (aggregation)

On this page本页内容

Definition定义

$filter

New in version 3.2.版本3.2中的新功能。

Selects a subset of an array to return based on the specified condition. 根据指定的条件选择要返回的数组子集。Returns an array with only those elements that match the condition. The returned elements are in the original order.返回仅包含与条件匹配的元素的数组。返回的元素按原始顺序排列。

$filter has the following syntax:语法如下所示:

{ $filter: { input: <array>, as: <string>, cond: <expression> } }
Field字段Specification规范文档
input An expression that resolves to an array.解析为数组的表达式
as Optional.可选。A name for the variable that represents each individual element of the input array. 表示输入数组中每个元素的变量的名称。If no name is specified, the variable name defaults to this.如果未指定名称,则变量名默认为this
cond An expression that resolves to a boolean value used to determine if an element should be included in the output array. 解析为布尔值的表达式,用于确定输出数组中是否应包含元素。The expression references each element of the input array individually with the variable name specified in as.表达式使用as中指定的变量名分别引用input数组的每个元素。

For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式

Behavior行为

Example示例Results结果
{
  $filter: {
     input: [ 1, "a", 2, null, 3.1, NumberLong(4), "5" ],
     as: "num",
     cond: { $and: [
        { $gte: [ "$$num", NumberLong("-9223372036854775807") ] },
        { $lte: [ "$$num", NumberLong("9223372036854775807") ] }
      ] }
  }
}
[ 1, 2, 3.1, NumberLong(4) ]

Example示例

A collection sales has the following documents:集合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 }
    ]
}

The following example filters the items array to only include documents that have a price greater than or equal to 100:以下示例筛选items数组,使其仅包含price大于或等于100的文档:

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

The operation produces the following results:该操作将产生以下结果:

{
   "_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" : [ ] }