Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Lọc phần tử mảng theo khoảng giá trị với $filter MongoDB

Tìm phần tử mảng thỏa mãn điều kiện range trong aggregation

Sử dụng $addFields với $filter để tạo mảng mới chỉ chứa phần tử trong khoảng giá trị.

Dữ liệu sản phẩm

> db.demo351.insertOne({
    "_id": "101",
    "ProductDetails": [
        { "ProductName": "Product-1", "ProductPrice": 500 },
        { "ProductName": "Product-2", "ProductPrice": 400 }
    ]
});
> db.demo351.insertOne({
    "_id": "102",
    "ProductDetails": [
        { "ProductName": "Product-3", "ProductPrice": 200 },
        { "ProductName": "Product-4", "ProductPrice": 800 }
    ]
});

Lọc ProductPrice 600-900 cho _id=102

> db.demo351.aggregate([
    { $match: { _id: "102" } },
    {
        $addFields: {
            ProductDetails: {
                $filter: {
                    input: "$ProductDetails",
                    cond: {
                        $and: [
                            { $gt: ["$$this.ProductPrice", 600] },
                            { $lt: ["$$this.ProductPrice", 900] }
                        ]
                    }
                }
            }
        }
    }
]);

Kết quả

{ "_id": "102", "ProductDetails": [{ "ProductName": "Product-4", "ProductPrice": 800 }] }

Đặc điểm: Document gốc không bị thay đổi. Pipeline trả về document với mảng đã lọc.