roschach
roschach

Reputation: 9336

Mongodb query: find documents having all elements of array in a given range

Suppose I have a collection whose documents have this structure

{
   ...
   "ts": [NumberLong("5"), NumberLong("7")]
   ...
}

where ts is an array of two Long elements, where the second is strictly bigger than the first one.

I want to retrieve all documents where all the elements of the array ts are within a range (bigger than a value but smaller than another).

Suppose the range is between 4 and 9; I am trying this query, but I find unexpected results:

db.segments.find({$nor: [{ "ts": {$gt:9, $lt:4}}]}).toArray()

Upvotes: 1

Views: 113

Answers (1)

turivishal
turivishal

Reputation: 36094

If you have fixed number of array length then you can use the index of array in query part,

db.segments.find({
  "ts.0": { $gt: 4 },
  "ts.1": { $lt: 9 }
}).toArray()

Playground

Upvotes: 1

Related Questions