MongoDB query to find value in array with multiple criteria (range)

To find values in an array within a specific range in MongoDB, use $elemMatch with $gt and $lt operators. This allows you to match documents where at least one array element satisfies multiple criteria.

Syntax

db.collection.find({
    "arrayField": {
        "$elemMatch": {
            "field": {
                "$gt": minValue,
                "$lt": maxValue
            }
        }
    }
});

Sample Data

db.demo341.insertMany([
    {
        "Name": "Chris",
        "productDetails": [
            { "ProductPrice": { "Price": 800 } },
            { "ProductPrice": { "Price": 400 } },
            { "ProductPrice": { "Price": 300 } }
        ]
    },
    {
        "Name": "David",
        "productDetails": [
            { "ProductPrice": { "Price": 1000 } },
            { "ProductPrice": { "Price": 1200 } },
            { "ProductPrice": { "Price": 1300 } }
        ]
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e53ed5cf8647eb59e5620a7"),
        ObjectId("5e53edc1f8647eb59e5620a8")
    ]
}

Example: Find Products in Price Range (600-900)

Find documents where at least one product has a price between 600 and 900 ?

db.demo341.find({
    "productDetails": {
        "$elemMatch": {
            "ProductPrice.Price": {
                "$gt": 600,
                "$lt": 900
            }
        }
    }
});
{
    "_id": ObjectId("5e53ed5cf8647eb59e5620a7"),
    "Name": "Chris",
    "productDetails": [
        { "ProductPrice": { "Price": 800 } },
        { "ProductPrice": { "Price": 400 } },
        { "ProductPrice": { "Price": 300 } }
    ]
}

How It Works

  • $elemMatch ensures at least one array element matches all the specified conditions
  • $gt: 600 matches prices greater than 600
  • $lt: 900 matches prices less than 900
  • The query returns the entire document when the condition is met

Conclusion

Use $elemMatch with range operators to find documents containing array elements within specific value ranges. This operator ensures all conditions must be satisfied by the same array element.

Updated on: 2026-03-15T02:33:20+05:30

530 Views

Advertisements