运算符 $setIsSubset 返回一个布尔值,该值指示一个数组是否是第二个数组的子集。 它将数组视为集,这意味着它忽略重复项和元素顺序。 如果第一个数组中的所有元素都存在于第二个数组中,则返回 true 它。 否则,它将返回 false。
Syntax
{
$setIsSubset: [ <array1>, <array2> ]
}
参数
| 参数 | Description |
|---|---|
<array1> |
要检查的数组,以查看其是否为子 <array2>集。 |
<array2> |
要检查的数组。 |
例子
请考虑商店集合中的这个示例文档。
{
"_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
},
{
"categoryName": "Towels",
"discountPercentage": 5
},
{
"categoryName": "Bathrobes",
"discountPercentage": 5
},
{
"categoryName": "Mattress Toppers",
"discountPercentage": 6
},
{
"categoryName": "Hand Towels",
"discountPercentage": 9
},
{
"categoryName": "Shower Heads",
"discountPercentage": 5
},
{
"categoryName": "Bedspreads",
"discountPercentage": 19
},
{
"categoryName": "Bath Mats",
"discountPercentage": 21
}
]
}
]
}
示例 1:确定销售类别是否为促销类别的子集
此查询确定商店的所有类别是否都包含在其促销折扣中,反之亦然。 此查询返回销售和促销括号下包括的类别。 它确认 sales 该值是特定促销类别的子集(但不执行相反作)。
db.stores.aggregate([
{ $match: {"_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f"} },
{
$project: {
name: 1,
salesCategories: "$sales.salesByCategory.categoryName",
promotionCategories: { $arrayElemAt: ["$promotionEvents.discounts.categoryName", 0] },
salesAreSubsetOfPromotions: {
$setIsSubset: [
"$sales.salesByCategory.categoryName",
{ $arrayElemAt: ["$promotionEvents.discounts.categoryName", 0] }
]
},
promotionsAreSubsetOfSales: {
$setIsSubset: [
{ $arrayElemAt: ["$promotionEvents.discounts.categoryName", 0] },
"$sales.salesByCategory.categoryName"
]
}
}
}
])
此查询返回以下结果。
[
{
"_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f",
"name": "First Up Consultants | Bed and Bath Center - South Amir",
"salesCategories": [
"Mattress Toppers"
],
"promotionCategories": [
"Bath Accessories",
"Pillow Top Mattresses",
"Bathroom Scales",
"Towels",
"Bathrobes",
"Mattress Toppers",
"Hand Towels",
"Shower Heads",
"Bedspreads",
"Bath Mats"
],
"salesAreSubsetOfPromotions": true,
"promotionsAreSubsetOfSales": false
}
]
相关内容
- 查看用于 从 MongoDB 迁移到 Azure DocumentDB 的选项。
- 详细了解 与 MongoDB 的功能兼容性。