tzn
tzn

Reputation: 125

Date filter in mongodb aggregation

I have a collection of user data entries that I need to group by usernames/ids and sort by number of times they appear for each user (a sort of top list of entries).

I managed to achieve it with this code:

Entries.aggregate([
    {
        $group: {
            _id: { uid: "$uid", name: "$name" },
            count: { $sum: 1 },
            utime: { $max: "$utime" }
        }
    },
    { $match: { count: { "$gt": 0 } } }
]);

Counting and matching all entries greater than 0 and giving precedence to older entries (with utime), if count is same on different users.

What I need now is to include a custom date range between which same grouping would occur, since this was applied to entire table. Native mongodb timestamps are in effect.

How can I achieve this? Any suggestions would be greatly appreciated.

Upvotes: 2

Views: 1341

Answers (1)

tzn
tzn

Reputation: 125

Thanks to @rickhg12hs suggestion I managed to get additional match filter. Only requirement is that ISODate format is required - otherwise nothing would return. Got it using moment library.

Entries.aggregate([
    {
        $match: {
            utime: {
                $gte: new Date(moment( startDate ).format('YYYY-MM-DD[T00:00:00.000Z]')),
                $lt: new Date(moment( endDate ).format('YYYY-MM-DD[T00:00:00.000Z]'))
            }
        }
    },
    {
        $group: {
            _id: { uid: "$uid", name: "$name" },
            count: { $sum: 1 },
            utime: { $max: "$utime" }
        }
    },
    { $match: { count: { "$gt": 0 } } }
]);

Upvotes: 2

Related Questions