2
votes

I've been trying to use the PHP MongoDB driver with the aggregation framework to filter over a few dates before piping into a $group, but the match isn't doing any filtering on dates, yet it works perfectly when filtering on strings and ints.

Here's my pipeline array and code:

  $date = new DateTime();
    $date->sub(new DateInterval('PT' . $hours . 'H'));
    $mdate = new MongoDate($date->getTimestamp());
    $ops = array(
        array('$match') => array(
            'whenField' => array(
                '$gt' => $mdate
            )
        )
    );

$results = $this->collection->aggregate($ops);

This should return all documents in my collection where 'whenField' is in the last 3 hours, but it returns every document in my collection. I can then switch the '$gt' to an '$lt' and it also returns every document in the collection. I've put this exact same match array as a filter and used find($filter) and it correctly filters. Are Date comparisons incompatible with the aggregation framework $match or have I made some kind of error?

1

1 Answers

3
votes

The $ops is wrong here, try:

$ops = array(
    array('$match' => array(
        'whenField' => array(
            '$gt' => $mdate
        )
    )
);

Instead