Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-range query in MongoDB

Tags:

mongodb

Is there a way to execute a single query for multiple, distinct ranges of documents in MongoDB?

e.g.

!(x > 10 && x < 20) && !(x > 25 && x < 30), where x is some field.

like image 209
paulkon Avatar asked Dec 29 '13 03:12

paulkon


People also ask

How do I search for multiples in MongoDB?

MongoDB provides the find() that is used to find multiple values or documents from the collection. The find() method returns a cursor of the result set and prints all the documents. To find the multiple values, we can use the aggregation operations that are provided by MongoDB itself.

What is MongoDB elemMatch?

Definition. $elemMatch. The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.

What is MongoDB aggregation pipeline?

What is the Aggregation Pipeline in MongoDB? The aggregation pipeline refers to a specific flow of operations that processes, transforms, and returns results. In a pipeline, successive operations are informed by the previous result. Let's take a typical pipeline: Input -> $match -> $group -> $sort -> output.

What is ISO date in MongoDB?

ISODate("2012-12-19T06:01:17.171Z") ISODate() is a helper function that's built into to MongoDB and wraps the native JavaScript Date object. When you use the ISODate() constructor from the Mongo shell, it actually returns a JavaScript Date object.


1 Answers

You can construct that query using $or with the $gte and $lte operators by inverting the boolean expression:

db.coll.find({
    $or: [{x: {$lte: 10}}, {x: {$gte: 20, $lte: 25}}, {x: {$gte: 30}}]
})
like image 161
JohnnyHK Avatar answered Sep 21 '22 02:09

JohnnyHK