Get stats analyse from collection

Hello, it may be very easy, but I don’t know how to get stats from a collection.
For example, I would like to know a percentage of categories given by a $match stage divided by the whole count of documents.
If I have a collection with 100 documents and a $match with only 20 matching documents I want to have an output like ‘20%’ or ‘0.2’
Thank you for reading !

Hi @philippe_cazabonne ,

Well it sounds like you are interested in just aggregating data to understand the precentages of counts whithin groups. This can be done with aggregation stages:

[{$facet: {
 total: [
  {
   $count: 'count'
  }
 ],
 groups: [
  {
   $group: {
    _id: '$category',
    count: {
     $count: {}
    }
   }
  }
 ]
}}, {$addFields: {
 total: {
  $first: '$total.count'
 }
}}, {$unwind: {
 path: '$groups'
}}, {$addFields: {
 precentageOfTotal: {
  $multiply: [
   {
    $divide: [
     '$groups.count',
     '$total'
    ]
   },
   100
  ]
 }
}}]

Consider the following example:

db.categories.insertMany([{category : "a"},{category : "a"},{category : "b"},{category : "c"}, {category : "b"}, {category : "c"}])

db.categories.aggregate([{$facet: {
 total: [
  {
   $count: 'count'
  }
 ],
 groups: [
  {
   $group: {
    _id: '$category',
    count: {
     $count: {}
    }
   }
  }
 ]
}}, {$addFields: {
 total: {
  $first: '$total.count'
 }
}}, {$unwind: {
 path: '$groups'
}}, {$addFields: {
 precentageOfTotal: {
  $multiply: [
   {
    $divide: [
     '$groups.count',
     '$total'
    ]
   },
   100
  ]
 }
}}])

{ total: 6,
  groups: { _id: 'c', count: 2 },
  precentageOfTotal: 33.33333333333333 }
{ total: 6,
  groups: { _id: 'b', count: 2 },
  precentageOfTotal: 33.33333333333333 }
{ total: 6,
  groups: { _id: 'a', count: 2 },
  precentageOfTotal: 33.33333333333333 }

As you can see each group is 33% of the total.

If you need another $match in the beginning to filter specefic information push the $match stage as the first…

Thanks
Pavel

It seems to be exactly what I need. I didn’t knew $facet stage!
Thanks a lot Pavel !

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.