$ifNull(条件表达式)

$ifNull 运算符用于计算表达式,如果表达式解析为 null,则返回指定的值。 如果想为可能不存在或可能具有 null 值的字段提供默认值,此运算符非常有用。

语法

{ $ifNull: [ <expression>, <replacement-value> ] }

parameters

说明
<expression> 要计算的表达式。
<replacement-value> 表达式计算结果为 null 时要返回的值

示例

让我们通过以下示例 json 来了解用法。

{
  "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
   "name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile",
  "location": {
    "lat": 60.1441,
    "lon": -141.5012
  },
  "staff": {
    "totalStaff": {
      "fullTime": 2,
      "partTime": 0
    }
  },
  "sales": {
    "salesByCategory": [
      {
        "categoryName": "DJ Headphones",
        "totalSales": 35921
      }
    ],
    "fullSales": 3700
  },
  "promotionEvents": [
    {
      "eventName": "Bargain Blitz Days",
      "promotionalDates": {
        "startDate": {
          "Year": 2024,
          "Month": 3,
          "Day": 11
        },
        "endDate": {
          "Year": 2024,
          "Month": 2,
          "Day": 18
        }
      },
      "discounts": [
        {
          "categoryName": "DJ Turntables",
          "discountPercentage": 18
        },
        {
          "categoryName": "DJ Mixers",
          "discountPercentage": 15
        }
      ]
    }
  ],
  "tag": [
    "#ShopLocal",
    "#SeasonalSale",
    "#FreeShipping",
    "#MembershipDeals"
  ]
}

示例 1:缺少 store.manager 字段的默认值

如果要确保 $staff.totalStaff.intern 字段始终为数字,则可以使用 $ifNullnull 值替换为 0

db.stores.aggregate([
  {
    $project: {
      name: 1,
      interns: { $ifNull: ["$staff.totalStaff.intern", 0] }
    }
  },
  // Limit the result to the first 3 documents
  { $limit: 3 } 
])

此查询将返回以下文档。

[
  {
    "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
    "name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile",
    "interns": 0
  },
  {
    "_id": "649626c9-eda1-46c0-a27f-dcee19d97f41",
    "name": "VanArsdel, Ltd. | Musical Instrument Outlet - East Cassie",
    "interns": 0
  },
  {
    "_id": "8345de34-73ec-4a99-9cb6-a81f7b145c34",
    "name": "Northwind Traders | Bed and Bath Place - West Oraland",
    "interns": 0
  }
]