duoduo
duoduo

Reputation: 21

How do I do multiple mongoose aggregate search?

I have a structure like below in MongoDB:

{
    memberId: 1236,
    platform: "PC",
    channel: "A",
    page: "B",
    ip: "192.168.10.1",
    isActive: true,
    createOn: "2017-02-19T09:28:43.688Z",
    isSubmit: false,
}

Now I need to do aggregate search as follows:

{

    memberId: 1236,
    platform: "PC",
    channel: "A",
    page: "B",
    pv: 111,
    uv: 10
}

uv (user views) is just based on pv (page views) distinct by ip.

How do I do multiple aggregate search?

I can only get one, either pv or uv, but can't get them all at the same time.

I use mongoose in node.js

Upvotes: 2

Views: 1659

Answers (1)

Bertrand Martel
Bertrand Martel

Reputation: 45432

You need first to identify what is your grouping _id. You can identify a single page with unique couple values of memberId,platform,channel and page, $sum all document count per $ip and add another $group to count distinct IP and $sum per page :

Data.aggregate([{
    $group: {
        _id: {
            memberId: "$memberId",
            platform: "$platform",
            channel: "$channel",
            page: "$page",
            ip: "$ip"
        },
        pv: {
            $sum: 1
        }
    }
}, {
    $group: {
        _id: {
            memberId: "$_id.memberId",
            platform: "$_id.platform",
            channel: "$_id.channel",
            page: "$_id.page"
        },
        pv: {
            $sum: "$pv"
        },
        uv: {
            $sum: 1
        }
    }
}], function(err, res) {
    if (err)
        console.log(err);
    else
        console.log(res);)
})

You can find sample output/output here

Upvotes: 1

Related Questions