Set multiple conditions in MongoDB and fetch value in a range

To set multiple conditions in MongoDB and fetch values in a range, use comparison operators like $gt (greater than) and $lt (less than) combined in a single query. This allows you to filter documents based on numeric ranges or multiple criteria.

Syntax

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

Sample Data

db.demo59.insertMany([
    { "Values": 50 },
    { "Values": 10 },
    { "Values": 58 },
    { "Values": 78 }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e286286cfb11e5c34d89923"),
        ObjectId("5e286288cfb11e5c34d89924"),
        ObjectId("5e28628ccfb11e5c34d89925"),
        ObjectId("5e28628fcfb11e5c34d89926")
    ]
}

Display all documents from the collection ?

db.demo59.find();
{ "_id": ObjectId("5e286286cfb11e5c34d89923"), "Values": 50 }
{ "_id": ObjectId("5e286288cfb11e5c34d89924"), "Values": 10 }
{ "_id": ObjectId("5e28628ccfb11e5c34d89925"), "Values": 58 }
{ "_id": ObjectId("5e28628fcfb11e5c34d89926"), "Values": 78 }

Example: Fetch Values in Range (51-70)

Get documents where Values is greater than 51 and less than 70 ?

db.demo59.find({ Values: { $gt: 51, $lt: 70 } });
{ "_id": ObjectId("5e28628ccfb11e5c34d89925"), "Values": 58 }

Key Points

  • Combine multiple operators using comma separation within the same field object.
  • Use $gte and $lte for inclusive ranges (greater/less than or equal).
  • Multiple conditions on different fields use separate field objects in the query.

Conclusion

MongoDB range queries use comparison operators like $gt and $lt combined in a single field condition. This efficiently filters documents within specified numeric ranges using multiple criteria.

Updated on: 2026-03-15T02:51:25+05:30

200 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements