共用方式為


$過濾器

運算子 $filter 可用來根據指定的條件篩選陣列中的元素。 當您需要在檔內操作或擷取特定數位元素時,這個運算子很有用。

語法

{
  $filter: {
    input: "<array>",
    as: "<string>",
    cond: "<expression>"
  }
}

參數

參數 Description
input 解析為陣列的表達式。
as 字串,指定輸入陣列中每個專案的變數名稱。
cond 表達式,決定是否要在輸出數位中包含專案。

範例

請參考商店集合中的此範例檔。

{
    "_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
          }
      ]
  }
]