MongoDB Aggregate Query, Logins Averages

Viewed 38
let pipeline = [{
    $match: {
        time: { $gt: 980985600 },
        user_id: mongoose.Types.ObjectId("60316a2e7641bd0017ced7b1")
    }
},
{
    $project: {
        newDate: { '$toDate': "$time" },
        user_id: '$user_id'
    }
},
{
    $group: {
        _id: { week: { $week: "$newDate" }, year: { $year: "$newDate" }},
        count: { $sum: 1 }
    }
}]

I am currently trying to perform an aggregate through mongoose to find the average logins per week for a specific user. So far I have been able to get to the total number of logins each week, but was curious if there was a way to find the average of these final groupings within the same function. How would I go about doing this?

1 Answers

Just add one last stage to your query:

{
    $group: {
        _id: null,
        avg: { $avg: "$count" }
    }
}

So try this:

let pipeline = [
    {
        $match: {
            time: { $gt: 980985600 },
            user_id: mongoose.Types.ObjectId("60316a2e7641bd0017ced7b1")
        }
    },
    {
        $project: {
            newDate: { '$toDate': "$time" },
            user_id: '$user_id'
        }
    },
    {
        $group: {
            _id: { week: { $week: "$newDate" }, year: { $year: "$newDate" } },
            count: { $sum: 1 }
        }
    },
    {
        $group: {
            _id: null,
            avg: { $avg: "$count" }
        }
    }
];
Related