Jesús Cota
Jesús Cota

Reputation: 535

Search inside a range of fields MongoDB

I have a DB on MongoDB, with a collection like this:

{
    "_id" : ObjectId("59a64b4cfb80146432aff6ac"),
    "name": "Mid Range",
    "end" : NumberLong("50000"),
    "start" : NumberLong("10000"),
},
{
    "_id" : ObjectId("59a64b4cfb80146432aff6ac"),
    "name": "Hi Range",
    "end" : NumberLong("100000"),
    "start" : NumberLong("150000"),
}

The user enters a number to validate: 125000, i need a query to get: "Hi Range" document. How can i do that? I'm trying to avoid code side, but if there is no choice it's ok.

Thanks!

Upvotes: 1

Views: 1155

Answers (3)

SJFJ
SJFJ

Reputation: 667

To avoid logic that determine that 12500 is Hi Range you could do something like this

db.collection.find( { $and: [ { start: { $lte: 125000 } }, { end: { $gt: 12500 } } ] } )

Upvotes: 0

Rafael Moreno
Rafael Moreno

Reputation: 80

You could even make do without the $and. You just need to set the query to find a result such that your number is less than or equal to its end and greater than or equal to its start. For example:

db.collection.find({start: {$lte: 125000}, end: {$gte: 125000}})

Note: Careful, if you want that range to include the start and end number, use $lte, $gte. Using $lt or $gt will not include it.

Upvotes: 3

hardy
hardy

Reputation: 901

You can do it like this -

db.find({name:/Hi Range/}) // regular Expression.

Upvotes: 0

Related Questions