MongoDB – How to Query elemMatch Date

mongodb

I have a document structure like this:

{
"_id" : ObjectId("5359816b036493327d7cae95"),
"_class" : "com.myproject.MyObjectDTO",
"signals" : [ 
    {
        "signalType" : "ABC",
        "quantity" : NumberLong(1),
        "date" : ISODate("2001-12-13T23:00:00.000Z")
    }, 
    {
        "signalType" : "ABD",
        "quantity" : NumberLong(1),
        "date" : ISODate("2001-12-16T23:00:00.000Z")
    }, 
    {
        "signalType" : "ABF",
        "quantity" : NumberLong(1),
        "date" : ISODate("2001-12-17T23:00:00.000Z")
    }, 
    {
        "signalType" : "ABG",
        "quantity" : NumberLong(1),
        "date" : ISODate("2001-12-18T23:00:00.000Z")
    },
    ...
}

with around 160 000 entries and 3000 signals per entry.

I tried to find documents with a date greater than an specified date (I'm using $date because I query through Spring Data):

db.analysisDTO.find(
      "signals" : {
         "$elemMatch" : { 
            "date" : { "$gte" : { "$date" : "2001-12-01T22:00:00.000Z"}})

The request takes more than 7 minutes and I get no result. Even if I change $gte to $lte, I don't get anything.

Is the request wrong?

Best Answer

The $date operator is a part of the MongoDB Extended JSON spec and that's what you get as default with mongoexport but you don't want to use it in the query criteria.

Try using the ISODate() constructor instead:

db.analysisDTO.find({"signals" : {
        "$elemMatch" : { 
           "date" : { 
             "$gte" : new ISODate("2001-12-01T22:00:00.000Z")}}}});

The reason for the 7 minute length is likely because the entire data set is being scanned into memory to check all fields.