Mongodb (v2.4.0) $match aggregate not working with

2020-03-26 07:09发布

问题:

I am using mongodb java driver thru maven repository (as below in pom.xml) to query transactions between date range with aggregate framwork. The java driver generates following $match that I tried to validate on mongo console and found that it does not work:

db.transactions.aggregate(
{ "$match" : 
    { 
        "created_at" : { "$gt" : { "$date" : "2001-04-12T12:00:00.000Z"} , "$lte" : { "$date" : "2020-04-13T12:00:00.000Z"}}
    }
}
)

If I remove $date block and replace it with ISOdate function and date string then it seem to be working. I failed to understand why it does not work in java ($match JSON - I had fetched from eclipse to try in mongo console and that do not work as well.)

pom.xml
<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>2.11.0</version>
</dependency>

does any one know why $date is not working with aggregate using MongoDB v2.4.0?

回答1:

I got it solved by removing the "" & $ prefix on the $date field of in $match. For you remove the same for $date, $gt & $lte

So that it should look like

db.transactions.aggregate(
{ "$match" : 
         { 
          'created_at': { 
                         $gt: "2001-04-12T12:00:00.000Z", 
                         $lt: "2020-04-13T12:00:00.000Z"
                        }
         }
});


回答2:

You have to format the date before passing onto $match aggregate.

Order.aggregate([
        {
          $match: {
            createdAt: {
              $gte: new Date(req.body.startDate),
              $lt: new Date(req.body.endDate)
            }
          }
        },
        {
          $lookup: {
            from: 'acbinstallerpayments',
            localField: "_id",
            foreignField: 'customerObjectID',
            as: 'installerPaymentDetails'
          }
        }
      ]);