$all(数组查询)

适用对象: MongoDB vCore

$all 运算符用于选择字段值为包含所有指定元素的数组的文档。 当你需要确保数组字段包含多个指定元素时,无论它们在数组中的顺序如何,此运算符都很有用。

语法

db.collection.find({ <field>: { $all: [ <value1> , <value2> ... ] } })

parameters

说明
field 要查询的字段。
<value1> , <value2> 必须全部出现在数组字段中的值。

示例

{
  "_id": "a57511bb-1ea3-4b26-bf0d-8bf928f2bfa8",
  "name": "Wide World Importers",
  "location": {
    "lat": 68.6378,
    "lon": -145.2852
  },
  "staff": {
    "totalStaff": {
      "fullTime": 1,
      "partTime": 5
    }
  },
  "sales": {
    "totalSales": 23399,
    "salesByCategory": [
      {
        "categoryName": "Smartphones",
        "totalSales": 5231
      },
      {
        "categoryName": "Laptops",
        "totalSales": 18168
      }
    ]
  },
  "promotionEvents": [
    {
      "eventName": "Unbeatable Bargain Bash",
      "promotionalDates": {
        "startDate": {
          "Year": 2023,
          "Month": 5,
          "Day": 17
        },
        "endDate": {
          "Year": 2023,
          "Month": 5,
          "Day": 25
        }
      },
      "discounts": [
        {
          "categoryName": "Video Games",
          "discountPercentage": 20
        },
        {
          "categoryName": "Tablets",
          "discountPercentage": 18
        }
      ]
    }
  ],
  "tag": [
    "#ShopLocal",
    "#FashionStore",
    "#SeasonalSale",
    "#FreeShipping",
    "#MembershipDeals"
  ]
}

示例 1:查找包含数组中所有指定元素的文档

该示例允许查询 stores 集合,以查找在 salesByCategory.categoryName 数组中同时包含元素 LaptopsSmartphones 的文档。

db.stores.find(
    { "sales.salesByCategory.categoryName": { $all: ["Laptops", "Smartphones"]} },
    { _id: 1, "sales.salesByCategory.categoryName": 1 }
).limit(2)

查询返回在 salesCategory 数组中同时包含 LaptopsSmartphones 的两个文档。

  {
    "_id": "a57511bb-1ea3-4b26-bf0d-8bf928f2bfa8",
    "sales": {
      "salesByCategory": [
        {
          "categoryName": "Smartphones"
        },
        {
          "categoryName": "Laptops"
        }
      ]
    }
  },
  {
    "_id": "ca56d696-5208-40c3-aa04-d4e245df44dd",
    "sales": {
      "salesByCategory": [
        {
          "categoryName": "Laptops"
        },
        {
          "categoryName": "Smartphones"
        }
      ]
    }
  }