$anyElementTrue (set 表达式)

适用对象: MongoDB vCore

运算符 $anyElementTrue 将数组计算为集并返回 true 数组 true 中的任何元素或等效 true项。 如果所有元素的计算结果为falsenull0undefined运算符返回false

语法

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

{
  $anyElementTrue: [ <array> ]
}

参数

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

示例:

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

{
  "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74",
  "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury",
  "location": {
    "lat": 70.1272,
    "lon": 69.7296
  },
  "staff": {
    "totalStaff": {
      "fullTime": 19,
      "partTime": 20
    }
  },
  "sales": {
    "totalSales": 151864,
    "salesByCategory": [
      {
        "categoryName": "Sound Bars",
        "totalSales": 2120
      },
      {
        "categoryName": "Home Theater Projectors",
        "totalSales": 45004
      },
      {
        "categoryName": "Game Controllers",
        "totalSales": 43522
      },
      {
        "categoryName": "Remote Controls",
        "totalSales": 28946
      },
      {
        "categoryName": "VR Games",
        "totalSales": 32272
      }
    ]
  }
}

示例 1:检查任何销售类别是否超过目标

此示例允许检查任何销售类别是否超过 40,000 个销售额的目标。

db.stores.aggregate([
  { $match: {"_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74"} },
  {
    $project: {
      salesByCategory: "$sales.salesByCategory",
      hasHighPerformingCategory: {
        $anyElementTrue: [
          {
            $map: {
              input: "$sales.salesByCategory",
              as: "category",
              in: { $gt: ["$$category.totalSales", 40000] }
            }
          }
        ]
      }
    }
  }
])

查询返回truehasHighPerformingCategory字段,因为其中一个类别的销售超过 40,000。

{
  "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74",
  "salesByCategory": [
    {
      "categoryName": "Sound Bars",
      "totalSales": 2120
    },
    {
      "categoryName": "Home Theater Projectors",
      "totalSales": 45004
    },
    {
      "categoryName": "Game Controllers",
      "totalSales": 43522
    },
    {
      "categoryName": "Remote Controls",
      "totalSales": 28946
    },
    {
      "categoryName": "VR Games",
      "totalSales": 32272
    }
  ],
  "hasHighPerformingCategory": true
}

示例 2:检查是否有任何促销活动具有高折扣

此示例允许检查任何促销活动是否提供超过 20%的折扣。

db.stores.aggregate([
  { $match: {"_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74"} },
  { $unwind: "$promotionEvents" },
  {
    $project: {
      eventName: "$promotionEvents.eventName",
      hasHighDiscount: {
        $anyElementTrue: [
          {
            $map: {
              input: "$promotionEvents.discounts",
              as: "discount",
              in: { $gte: ["$$discount.discountPercentage", 20] }
            }
          }
        ]
      }
    }
  }
])

查询返回 true ,考虑到我们至少有一个促销活动,折扣超过 20%。

{
  "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74",
  "eventName": "Massive Markdown Mania",
  "hasHighDiscount": true
}