Search code examples
mongodbsails.jssails-mongo

SaisJS - The condition in $match is not working


This is how my code looks like:

User.native(function (err, collection) {
        if (err) throw err;
        collection.aggregate([
            {
                $match: {
                    id: req.params.id,
                    createdAt: {">=": start, "<=": end}
                }
            },
            {
                $group: {
                    _id: "$class",
                    count: {$sum: 1},
                    jointime: {$max: "$endtime"}
                }
            }
        ]

The createdAt is what I added for filtering the collection by time, but after I did that, there's no result returned.

I thought it was caused by the date type, because the createdAt is date in MongoDB. But when I tried with this, I can get the correct data.

User.find({}, {id: req.params.childid, createdAt: {">=": start, "<=": end}}, function (err, result) {
        console.log("CreatedAt: " + result[0].createdAt);
        console.log("Result length: " + result.length);
    });

So, I think it's nothing to do with the date. Is there anything different in aggregate?


Solution

  • You should use $gte and $lte instead of ">=" and "<=" in $match operator.

     $match: {
             id: req.params.id,
             createdAt: {$gte: start, $lte: end}
     }