Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo: dates in match aggregate query seem to be ignored

I'm trying to run an aggregation statement in my mongo db. I have a document whose structure is (at least) as follows:

{
   "_id": ObjectId,
   "date": ISODate,
   "keywordGroupId": NumberLong,
   "ranking": NumberLong,
}

I would like to run an aggregation statement that aggregates the 'ranking' field for a given 'keywordGroupId' and a given 'date' interval.

I have been trying with the following aggregate command:

{ 
    aggregate : "KeywordHistory", 
    pipeline : [
        { $match: { keywordGroupId: 75 , "$date": {$gte: ISODate("2013-01-01T00:00:00.0Z"), $lt: ISODate("2013-02-01T00:00:00.0Z")}} },
        { $group: { _id: { null }, count: { $sum: "$ranking" } } }
    ]
}

This command executes without errors and returns a result. If I try to change the value for the 'keywordGroupId' field, the command returns a different value, so I assume that the $match statement works for that field (NumberLong). Though, if I change the 'date' range and I specify a time interval for which I don't have any data in the database, it still returns a result (I would actually expect an empty result set). So I have to assume that the $match statement is ignoring the date interval specified.

Can anyone help me with this point?

like image 879
Marco Avatar asked Feb 22 '13 12:02

Marco


1 Answers

Remove the $ prefix on the $date field of your $match:

{ $match: { 
    keywordGroupId: 75, 
    date: {$gte: ISODate("2013-01-01T00:00:00.0Z"), $lt: ISODate("2013-02-01T00:00:00.0Z")}
}},

You only use the $ prefix when the field name is used in a value, not as a key.

like image 115
JohnnyHK Avatar answered Oct 18 '22 22:10

JohnnyHK