$ifNull (aggregation)

On this page本页内容

Definition定义

$ifNull

Changed in version 5.0.在版本5.0中更改

The $ifNull expression evaluates input expressions for null values and returns:$ifNull表达式计算输入表达式的空值并返回:

  • The first non-null input expression value found.找到的第一个非空输入表达式值。
  • A replacement expression value if all input expressions evaluate to null.如果所有输入表达式的值都为空,则替换表达式值。

$ifNull treats undefined values and missing fields as null.将未定义的值和缺少的字段视为空。

Syntax:语法:

{
   $ifNull: [
      <input-expression-1>,
      ...
      <input-expression-n>,
      <replacement-expression-if-null>
   ]
}

In MongoDB 4.4 and earlier versions, $ifNull only accepts a single input expression:在MongoDB 4.4和早期版本中,$ifNull只接受一个输入表达式:

{
   $ifNull: [
      <input-expression>,
      <replacement-expression-if-null>
   ]
}

Examples示例

This inventory collection is used in the examples:inventory集合用于以下示例:

db.inventory.insertMany( [
   { "_id" : 1, "item" : "buggy", description: "toy car", "quantity" : 300 },
   { "_id" : 2, "item" : "bicycle", description: null, "quantity" : 200 },
   { "_id" : 3, "item" : "flag" }
] )

Single Input Expression单输入表达式

The following example uses $ifNull to return:以下示例使用$ifNull返回:

  • description if it is non-null.如果description非空,则为description
  • "Unspecified" string if description is null or missing.如果description为空或缺失,则为"Unspecified"字符串。
db.inventory.aggregate(
   [
      {
         $project: {
            item: 1,
            description: { $ifNull: [ "$description", "Unspecified" ] }
         }
      }
   ]
)

Output:输出:

{ "_id" : 1, "item" : "buggy", "description" : "toy car" }
{ "_id" : 2, "item" : "bicycle", "description" : "Unspecified" }
{ "_id" : 3, "item" : "flag", "description" : "Unspecified" }

Multiple Input Expressions多输入表达式

New in version 5.0.在版本5.0中新增

The following example uses $ifNull to return:以下示例使用$ifNull返回:

  • description if it is non-null.如果description非空,则为description
  • quantity if description is null or missing and quantity is non-null.如果description为空或缺失,而quantity为非空,则为quantity
  • "Unspecified" string if description and quantity are both null or missing.如果descriptionquantity都是空或缺失,则为"Unspecified"字符串。
db.inventory.aggregate(
   [
      {
         $project: {
            item: 1,
            value: { $ifNull: [ "$description", "$quantity", "Unspecified" ] }
         }
      }
   ]
)

Output:输出:

{ "_id" : 1, "item" : "buggy", "value" : "toy car" }
{ "_id" : 2, "item" : "bicycle", "value" : 200 }
{ "_id" : 3, "item" : "flag", "value" : "Unspecified" }
←  $hour (aggregation)$in (aggregation) →