Mongodb query with between valid range

Viewed 23

I have a collection that has a field similar to the following:

working_range: [
   {
       from: 25000
       to: 50000
   },
   {
       from: 60000,
       to: 70000
   }
]

In short it is array of objects with SECONDS from midnight as value from when to when something is working.

Now I want to say I want to schedule myself to the working place.

Example 1: schedule from 26000s to 27000s would work because that place is working between 25k to 50k.

Example 2: schedule from 20000s to 27000s would not work because from needs to be at least 25k.

Example 3: schedule from 55000 to 6500 would not work because valid ranges are either 25k to 50k or 60k to 70k.

Example 4: schedule from 65000 to 70000 would work because it belongs in range 60k to 70k.

I have no idea how to make this query work in all cases...

1 Answers

I ended up doing:

"$elemMatch": {
     "$and": [
         {
             "from": {
                 "$lte": from_seconds
             }
         },
         {
             "to": {
                "$gte": to_seconds
            }
        }
    ]
}

Rushed for the question...I was checking in code when is not valid instead of when it is valid so it made my query a lot harder to figure out.

Related