Home > Blockchain >  Based on ids, count how many user in mongo aggregation
Based on ids, count how many user in mongo aggregation

Time:02-18

So I have a collection like this:

    {
     'region': '111',
     'fruit': 'apple'
    }
    {
     'region': '111',
     'fruit': 'apple'
    }
    {
     'region': '222',
     'fruit': 'orange'
    }
    {
     'region': '222',
     'fruit': 'apple'
    }
 {
     'region': '333',
     'fruit': 'grapes'
    }
 {
     'region': '333',
     'fruit': 'grapes'
    }
 {
     'region': '333',
     'fruit': 'grapes'
    }
{
     'region': '333',
     'fruit': 'orange'
    }

I need like this

{'111': 1, '222': 2, '333': 2} which key is religion and value should be number of different fruits for that religion. 333 have 3 grapes and 1 orange but it should taken as 2 only because it have 2 different fruits. can anyone help me...

CodePudding user response:

Getting the output you requested seems overly complicated, especially with wanting the region value to become a key. The aggregation pipeline already provides a way to get grouped totals, which would provide a document-per-region with a total for the number in each region. You could use two group stages to get the totals you are looking for, like this:

[
  {
    $group: 
    {
      _id: { region: "$region", fruit: "$fruit" },
      count: { $sum: 1 }
    }
  },
  {
    $group:
    {
      _id: "$_id.region",
      count: { $sum: 1 }
    }
  }
]

The output from this aggregation would look like this:

{ _id: '111', count: 1 },
{ _id: '222', count: 2 },
{ _id: '333', count: 2 }

I suspect that this will be a much easier to consume output, as the count of documents returned is the number of regions (versus having to count the number of keys in the single document returned that you asked for in your question).

  • Related