user1438162
user1438162

Reputation: 1463

Mongodb Aggregate: Nested totals

I am trying to generate a report from our mongo db that tallies up the unique visits by country code per referral site. I'd like to use aggregation as I've heard it is quite fast and performance here is an issue.

We have an account db that has a country code and last referral site associated with each account.

{
   account:"user123",
   CountryCode:"CA",
   ReferalSite:"Google",
   lastLogin:"someisodate"
}

Conceptually, I can write the javascript in a few minutes.

For each unique vistor in accounts db;
    visits[vistor.country_code][vistor.refferal_site]+= 1;

Is this query possible with a db.accounts.aggregate()? Or is a map/reduce the better way to go about this.

Thanks in advance,

Upvotes: 0

Views: 110

Answers (1)

attish
attish

Reputation: 3150

You can run two groups one after another :

    db.collection.aggregate([
        {$group:{_id:{account:'$account', CountryCode:'$CouintryCode', ReferalSite:'$ReferalSite'}}, {number:1}},
        {$group:{_id:{CountryCode:'$_id.CountryCode', ReferalSite:'$_id.ReferalSite'}}, {number:{$sum:'$number'}}}])

Upvotes: 1

Related Questions