Vojtěch Ruschka
Vojtěch Ruschka

Reputation: 43

MongoDB query with lt and gt operators

Please can anybody help with this MongoDB query?

I wrote this query:

db.getCollection('epg').find({
'programs.start':{'$lte': new ISODate('2015-07-30 19:10:00.000Z')},
'programs.end':{'$gte': new ISODate('2015-07-30 19:10:00.000Z')}},
{'programs.$':1, 'name':1, 'id':1, 'broadcastDay':1})

MongoDB returns me this document:

{
    "_id" : ObjectId("55ba36cb68057b06d80f766a"),
    "id" : "2",
    "broadcastDay" : "2015-07-30",
    "name" : "Prima COOL",
    "programs" : [ 
        {
            "serialNumber" : "11/340/00039/0024",
            "start" : ISODate("2015-07-30T19:25:00.000Z"),
            "end" : ISODate("2015-07-30T19:44:00.000Z")
        }
    ]
}

Start and end in returned document don't match the query. Does anybody know, why MongoDB returns this document? I expect, that result will be empty (there is no matching document in my collection "epg").

Upvotes: 1

Views: 815

Answers (1)

sheilak
sheilak

Reputation: 5873

Your query will match any document where some item in the programs array matches the start condition, and some element matches the end condition. As per @Philipp’s comment above, you should use $elemMatch to do the query if you want to match documents where some item in programs matches both conditions.

You are using the positional $ operator to return only the first element of the array that matches the query. The element returned matches the end condition but if you pull back the whole document by ID, you’ll see there are more entries in programs and one of those other entries matches the start condition.

Upvotes: 1

Related Questions