$setIsSubset演算子は、1 つの配列が 2 番目の配列のサブセットであるかどうかを示すブール値を返します。 配列はセットとして扱われます。つまり、重複と要素の順序は無視されます。 最初の配列内のすべての要素が 2 番目の配列に存在する場合は、 true を返します。 それ以外の場合は、falseを返します。
構文
{
$setIsSubset: [ <array1>, <array2> ]
}
パラメーター
| パラメーター | Description |
|---|---|
<array1> |
<array2>のサブセットであるかどうかを確認する配列。 |
<array2> |
チェック対象の配列。 |
例示
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
},
{
"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
}
]