MongoDB Aggregate in Node.js with Mongoose did not get correct results

438 Views Asked by At

I'm trying to use aggregate to get some specific results by a ObjectId field and a Date field. When i use only ObjectId to match the results, it worked correctly, but after added Date conditions, it just returns nothing. Here is my aggregate codes:

FlowerAssignment.aggregate({
            $match: {
                class: new MongoTypes.ObjectId(current_class),
                time: {
                    $lte: moment().startOf('month').toDate(),
                    $gte: moment().endOf('month').toDate()
                }
            }
        })
        .project({
            student: 1,
            name: '$studentInfo.name',
            avatar: '$studentInfo.avatar',
            flowerInfo: 1
        }).group({
            _id: '$student',
            name: {
                $first: '$name'
            },
            avatar: {
                $first: '$avatar'
            },
            flowers: {
                $sum: 1
            }
        }).exec(function (err, results) {});

What's wrong with the match conditions...I've really got no ideas....

1

There are 1 best solutions below

0
On BEST ANSWER

Your $match object contains mutually exclusive terms as, unless it's an array, the time field of a document can't simultaneously be both before the start of the month and after the end of the month.

I'm assuming you've got those backwards and it should be:

$match: {
    class: new MongoTypes.ObjectId(current_class),
    time: {
        $gte: moment().startOf('month').toDate(),
        $lte: moment().endOf('month').toDate()
    }
}