$isArray (数组表达式)

适用对象: MongoDB vCore

$isArray 运算符用于确定指定的值是否为数组。 如果值为数组,则返回 true,否则返回 false。 此运算符通常用于聚合管道,以根据字段是否包含数组来筛选或转换文档。

语法

$isArray 运算符的语法如下所示:

{ $isArray: <expression> }

参数

说明
<expression> 任何可解析为要检查的值的有效表达式。

让我们通过以下示例 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"
  ]
}

下方示例演示 $isArray 运算符的用法。

示例 1:检查字段是否为数组

检查 salesByCategory 子文档中的 sales 字段是否为所有文档中均存在的数组。

db.stores.aggregate([
  {
    $project: {
      _id: 1,
      isSalesByCategoryArray: { $isArray: "$sales.salesByCategory" }
    }
  },
 // Limit the result to the first 3 documents
  { $limit: 3 } 
])

此查询将返回以下文档。

[
  {
    "_id": "649626c9-eda1-46c0-a27f-dcee19d97f41",
    "isSalesByCategoryArray": true
  },
  {
    "_id": "8345de34-73ec-4a99-9cb6-a81f7b145c34",
    "isSalesByCategoryArray": true
  },
  {
    "_id": "57cc4095-77d9-4345-af20-f8ead9ef0197",
    "isSalesByCategoryArray": true
  }
]

示例 2:根据数组字段筛选文档

我们还可以使用 $isArray 来筛选 promotionEvents 字段为数组的文档。

db.stores.aggregate([
  {
    $match: {
      $expr: { $isArray: "$promotionEvents" }
    }
  },
  // Limit the result to the first 3 documents
  { $limit: 3 },
   // Include only _id and name fields in the output 
  { $project: { _id: 1, name: 1 } }    
])

此查询将返回以下文档。

[
  {
    "_id": "649626c9-eda1-46c0-a27f-dcee19d97f41",
    "name": "VanArsdel, Ltd. | Musical Instrument Outlet - East Cassie"
  },
  {
    "_id": "8345de34-73ec-4a99-9cb6-a81f7b145c34",
    "name": "Northwind Traders | Bed and Bath Place - West Oraland"
  },
  {
    "_id": "57cc4095-77d9-4345-af20-f8ead9ef0197",
    "name": "Wide World Importers | Bed and Bath Store - West Vitafort"
  }
]