How to find all posts whose values are between x(number) and y(number)


#1

I have posts and each post has a value called Numbers that contains an array of 2 Numbers
so it looks like
"numbers": [
3,
5
]

I am using Post.find(); to call all the posts. How can I can call all the posts whose numbers are between x and y values? So if x is 0 and y is 10, how can I find all the post whos numbers are both between 0 and 10?(if that makes sense);

As of now I can only find the post find on specific numbers.
ex:
Posts.find({numbers: [
3,
5
]})

Any input is greatly appreciated it and please let me know if I need to explain the question better.

Thanks!


#2

I’m sure there are more efficient ways to write this query and perhaps even those that can scale them to arrays of any size, but since we are working with arrays of known size, this would do the job

var x=1,y=5;

Posts.find({
  $and: [
    {'numbers.0': {$gt: x}},
    {'numbers.0': {$lt: y}},
    {'numbers.1': {$gt: x}},
    {'numbers.1': {$lt: y}}
  ]
});

#3

lol, I had similar selector, but was not sure if numbers.1 or numbers.[1] :smiley:

And mine was more of a translation of his request :smiley:

Posts.find({
  $and: [
    {
      'numbers.0': {
        $and: [
          { $gt: 0},
          { $lt: 10}
        ]
      }
    },
    {
      'numbers.1': {
        $and: [
          { $gt: 0},
          { $lt: 10}
        ]
      }
    }
  ]
})

#4

Thank you both very much for your solutions. Both of them did exactly what I am looking for :slight_smile: