$all 運算子可用來選取欄位的值是包含所有指定元素的陣列的文件。 當您需要確保陣列欄位包含多個指定的元素時,不論其在陣列中的順序為何,此運算子就很有用。
語法
db.collection.find({
field : {
$all: [ < value1 > , < value2 > ]
}
})
參數
| 參數 | Description |
|---|---|
field |
要查詢的欄位。 |
<value1> , <value2> |
必須全部存在於陣列欄位中的值。 |
範例
請參考商店集合中的此範例檔。
{
"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
"name": "First Up Consultants | Beverage Shop - Satterfieldmouth",
"location": {
"lat": -89.2384,
"lon": -46.4012
},
"staff": {
"totalStaff": {
"fullTime": 8,
"partTime": 20
}
},
"sales": {
"totalSales": 75670,
"salesByCategory": [
{
"categoryName": "Wine Accessories",
"totalSales": 34440
},
{
"categoryName": "Bitters",
"totalSales": 39496
},
{
"categoryName": "Rum",
"totalSales": 1734
}
]
},
"promotionEvents": [
{
"eventName": "Unbeatable Bargain Bash",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 6,
"Day": 23
},
"endDate": {
"Year": 2024,
"Month": 7,
"Day": 2
}
},
"discounts": [
{
"categoryName": "Whiskey",
"discountPercentage": 7
},
{
"categoryName": "Bitters",
"discountPercentage": 15
},
{
"categoryName": "Brandy",
"discountPercentage": 8
},
{
"categoryName": "Sports Drinks",
"discountPercentage": 22
},
{
"categoryName": "Vodka",
"discountPercentage": 19
}
]
},
{
"eventName": "Steal of a Deal Days",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 9,
"Day": 21
},
"endDate": {
"Year": 2024,
"Month": 9,
"Day": 29
}
},
"discounts": [
{
"categoryName": "Organic Wine",
"discountPercentage": 19
},
{
"categoryName": "White Wine",
"discountPercentage": 20
},
{
"categoryName": "Sparkling Wine",
"discountPercentage": 19
},
{
"categoryName": "Whiskey",
"discountPercentage": 17
},
{
"categoryName": "Vodka",
"discountPercentage": 23
}
]
}
]
}
範例 1:尋找包含陣列中所有指定元素的文件
此查詢會擷取包含元素 Laptops 和 Smartphones 陣列內 salesByCategory.categoryName 的文件。
db.stores.find({
"sales.salesByCategory.categoryName": {
$all: ["Laptops", "Smartphones"]
}
}, {
_id: 1,
"sales.salesByCategory.categoryName": 1
}).limit(2)
此查詢傳回的前兩個結果是:
[
{
"_id": "a57511bb-1ea3-4b26-bf0d-8bf928f2bfa8",
"sales": {
"salesByCategory": [
{
"categoryName": "Smartphones"
},
{
"categoryName": "Laptops"
}
]
}
},
{
"_id": "ca56d696-5208-40c3-aa04-d4e245df44dd",
"sales": {
"salesByCategory": [
{
"categoryName": "Laptops"
},
{
"categoryName": "Smartphones"
}
]
}
}
]
相關內容
- 檢視從 MongoDB 遷移到 Azure DocumentDB 的選項。
- 閱讀有關 與 MongoDB 的功能相容性的更多資訊。