1

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").

  • I don't know how you got this document back. But the result should be empty and is empty when I tested it. – user353gre3 Jul 30 '15 at 16:25
  • 1
    Is that really the only entry of the `programs` array? When there are more entries, you will have to use `$elemMatch` or each criteria will be tested separately against a match in any entry. – Philipp Jul 30 '15 at 16:34
  • possible duplicate of [Retrieve only the queried element in an object array in MongoDB collection](http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) – Blakes Seven Jul 31 '15 at 03:23

1 Answers1

1

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.

sheilak
  • 5,833
  • 7
  • 34
  • 43