$allElementsTrue (set 表达式)

适用对象: MongoDB vCore

运算符 $allElementsTrue 将数组计算为集,如果 true 数组 false 中没有元素或等效 false (例如 null0undefined)。 如果任何元素的计算结果 false为,则运算符返回 false

语法

$allElementsTrue 运算符的语法如下:

{
  $allElementsTrue: [ <array> ]
}

参数

DESCRIPTION
array 要计算的表达式数组。 如果数组为空, $allElementsTruetrue返回 。

示例:

让我们了解数据集中示例 JSON 的 stores 用法。

{
  "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f",
  "name": "First Up Consultants | Bed and Bath Center - South Amir",
  "location": {
    "lat": 60.7954,
    "lon": -142.0012
  },
  "staff": {
    "totalStaff": {
      "fullTime": 18,
      "partTime": 17
    }
  },
  "sales": {
    "totalSales": 37701,
    "salesByCategory": [
      {
        "categoryName": "Mattress Toppers",
        "totalSales": 37701
      }
    ]
  },
  "promotionEvents": [
    {
      "eventName": "Price Drop Palooza",
      "promotionalDates": {
        "startDate": {
          "Year": 2024,
          "Month": 9,
          "Day": 21
        },
        "endDate": {
          "Year": 2024,
          "Month": 9,
          "Day": 30
        }
      },
      "discounts": [
        {
          "categoryName": "Bath Accessories",
          "discountPercentage": 18
        },
        {
          "categoryName": "Pillow Top Mattresses",
          "discountPercentage": 17
        },
        {
          "categoryName": "Bathroom Scales",
          "discountPercentage": 9
        }
      ]
    }
  ]
}

示例 1:检查所有折扣百分比是否高于零

假设你想要验证促销事件中的所有折扣百分比是否大于零。

db.stores.aggregate([
  { $match: {"_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f"} },
  { $unwind: "$promotionEvents" },
  {
    $project: {
      allDiscountsValid: {
        $allElementsTrue: [
          {
            $map: {
              input: "$promotionEvents.discounts.discountPercentage",
              as: "discount",
              in: { $gt: ["$$discount", 0] }
            }
          }
        ]
      }
    }
  }
])

该查询显示所有折扣百分比是否大于零。

{
  "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f",
  "allDiscountsValid": true
}