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

Tìm giá trị trong mảng theo khoảng (range) với $elemMatch MongoDB

Lọc phần tử mảng thỏa mãn nhiều điều kiện so sánh

Sử dụng $elemMatch trong $match stage của aggregation để tìm document có ít nhất một phần tử thỏa mãn tất cả điều kiện.

Dữ liệu giá sản phẩm

> db.demo341.insertOne({
    "Name": "Chris",
    "productDetails": [
        {"ProductPrice": {"Price": 800}},
        {"ProductPrice": {"Price": 400}},
        {"ProductPrice": {"Price": 300}}
    ]
});
> db.demo341.insertOne({
    "Name": "Chris",
    "productDetails": [
        {"ProductPrice": {"Price": 1000}},
        {"ProductPrice": {"Price": 1200}},
        {"ProductPrice": {"Price": 1300}}
    ]
});

Tìm document có Price trong khoảng 600-900

> db.demo341.aggregate([
    {
        $match: {
            "productDetails": {
                $elemMatch: {
                    "ProductPrice.Price": { $gt: 600, $lt: 900 }
                }
            }
        }
    }
]).pretty();

Kết quả

{
    "_id": ObjectId("..."),
    "Name": "Chris",
    "productDetails": [
        {"ProductPrice": {"Price": 800}},
        {"ProductPrice": {"Price": 400}},
        {"ProductPrice": {"Price": 300}}
    ]
}

Quan trọng: $elemMatch đảm bảo cùng một phần tử thỏa cả $gt và $lt. Nếu dùng dot notation đơn giản, có thể match phần tử khác nhau cho mỗi điều kiện.