1

I have the following code:

db.company_suppressions.aggregate([
    {$match: {company_id: ObjectId('5edd3f71c130ea5378977d41')}},
    {$group: {"_id": null, emails: {$push: "$email"}, phones: {$push: "$phone"} } },
    {$project: {emails: true, phones: true, _id: false}}
])

It returns this, which is exactly what I want:

[
  {
    "emails": ["aashby71@yahoo.com", "alidsdvz@yahoo.com", "alw100794@gmail.com", "alysenhurt8@gmail.com"],
    "phones": ["3331234451", "3331234454", "7423742992", "1740742393", "4321221133"]
  }
]

But sometimes I need to only see the counts of the corresponding fields. Is there a simple way to tweak that aggregation pipeline to have it return this:

[
  {
    "emails": 4,
    "phones": 5
  }
]
codemonkey
  • 7,325
  • 5
  • 22
  • 36

1 Answers1

1

You can use $size to count an array,

db.collection.aggregate([
  {
    $project: {
      emails: {
        $size: "$emails"
      },
      phones: {
        $size: "$phones"
      }
    }
  }
])

Working Mongo playground

varman
  • 8,704
  • 5
  • 19
  • 53