0

I have a simple collection with documents of vendors that looks like this:

{
  "name": "Nick's Burger",
  "country": "AT",
  "branches": [
    {
      "branchId": "12535",
      "branchName": "Nick's Burger Branch One",
      "branchAddress": "Somewhere in austria"
    },
    {
      "branchId": "38267",
      "branchName": "Nick's Burger Branch Two",
      "branchAddress": "Somewhere else in austria"
    }
  ]
}

For each of the vendors there is a list of "branches", and I want to count how many branches all the vendors from "country" AT have.

tried something like:

db.vendors.find({country: "AT"}, {$size: {branches: 1}}).count()

but that only gives me the count of vendors from AT...

JohnBigs
  • 2,691
  • 3
  • 31
  • 61
  • From the marked duplicates, you can deduce the pipeline as `db.vendors.aggregate([ { '$match': { 'country': "AT" } }, { '$project': { 'branchesCount': { '$size': '$branches' } } } ])` – chridam Jan 08 '19 at 13:24
  • @chridam but I dont see there how can I get the sum of branchesCount... – JohnBigs Jan 08 '19 at 13:28
  • @chridam my question was how to sum it up not how to print it with sum of each of the document array. i want to know sum of all arrays – JohnBigs Jan 08 '19 at 13:50
  • Try `db.vendors.aggregate[{"$match":{"country":"AT"}},{"$group":{"_id":null,"branchesCount":{"$sum":{"$size":"$branches"}}}}])` – s7vr Jan 08 '19 at 14:08
  • @Veeram thanks buddy, thats what i needed :) – JohnBigs Jan 08 '19 at 14:21

0 Answers0