$filter演算子は、指定した条件に基づいて配列から要素をフィルター処理するために使用されます。 この演算子は、ドキュメント内の特定の配列要素を操作または取得する必要がある場合に便利です。
構文
{
$filter: {
input: "<array>",
as: "<string>",
cond: "<expression>"
}
}
パラメーター
| パラメーター | Description |
|---|---|
input |
配列に解決される式。 |
as |
入力配列内の各要素の変数名を指定する文字列。 |
cond |
出力配列に要素を含めるかどうかを決定する式。 |
例示
stores コレクションのこのサンプル ドキュメントについて考えてみましょう。
{
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
"name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile",
"location": {
"lat": 60.1441,
"lon": -141.5012
},
"staff": {
"totalStaff": {
"fullTime": 2,
"partTime": 0
}
},
"sales": {
"salesByCategory": [
{
"categoryName": "DJ Headphones",
"totalSales": 35921
},
{
"categoryName": "DJ Cables",
"totalSales": 1000
}
],
"fullSales": 3700
},
"promotionEvents": [
{
"eventName": "Bargain Blitz Days",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 3,
"Day": 11
},
"endDate": {
"Year": 2024,
"Month": 2,
"Day": 18
}
},
"discounts": [
{
"categoryName": "DJ Turntables",
"discountPercentage": 18
},
{
"categoryName": "DJ Mixers",
"discountPercentage": 15
}
]
},
{
"eventName": "Discount Delight Days",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 5,
"Day": 11
},
"endDate": {
"Year": 2024,
"Month": 5,
"Day": 18
}
}
}
],
"tag": [
"#ShopLocal",
"#FashionStore",
"#SeasonalSale",
"#FreeShipping",
"#MembershipDeals"
]
}
例 1: 条件でフィルター処理された要素を取得する
このクエリでは、 totalSalesに基づいて販売カテゴリをフィルター処理する方法を示します。
db.stores.aggregate([{
$match: {
_id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5"
}
},
{
$project: {
filteredSalesByCategory: {
$filter: {
input: "$sales.salesByCategory",
as: "item",
cond: {
$gt: ["$$item.totalSales", 10000]
}
}
}
}
}
])
このクエリは、次の結果を返します。
[
{
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
"filteredSalesByCategory": [
{
"categoryName": "DJ Headphones",
"totalSales": 35921
}
]
}
]
関連コンテンツ
- MongoDB から Azure DocumentDB に移行するためのオプションを確認します。
- MongoDB との機能の互換性について詳しくは、こちらをご覧ください。