2

I have mongo documents:

{
    id:1
    time:[
        1,
        2,
        10
    ]
}
{
    id:2
    time:[
        1,
        4,
        8,
        10
]
}

I want find all documents, which have time between 3 and 5 or between 7 or 9 (document with id 2). I dont know how do this.

I try:

mongo.find( $or : [{time:{$gte:3, $lte:5}}, {time:{$gte:7, $lte:9}}] )

and mongo returns documents with id 1 and 2, but i need id2 with time[4, 8].

How to apply a condition to each element of the array, but NOT to entire array?

p.s. Size array "time" maybe different

2 Answers 2

3

If you're using the 'time' array as a placeholder for another array of storage then the previous comment with elemMatch should help you as this should cope with other numerical searches such as exam scores.

However, if you are using it for processing dates / times etc. then you might be better of working with unix timestamps for storage as this is done via integers and quite easy to search and store in mongodb and support is easy to come by for the majority of programming languages out there. (example in php: mktime() and DateTime::getTimestamp()).

Sign up to request clarification or add additional context in comments.

Comments

2

Try using the $elemMatch operator:

mongo.find({time:{$elemMatch: {$gte:3,$lte:5}}})

Like with:

mongo.find( 
  {
    $or: [
      {time:{$elemMatch: {$gte:3,$lte:5}}},
      {time:{$elemMatch: {$gte:7,$lte:9}}}
    ]
  }
)

1 Comment

what if time was an array of objects rather than an array of numbers?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.