3

On MongoDB I have a collection like this: -

{
  org: "org",
  departments: [
    {
       name: "abc",
       employees: [
         { name: "number1" },
         { name: "number2" },
         { name: "number3" },
       ]
    },
    {
       name: "mno",
       employees: [
         { name: "number4" },
         { name: "number5" }
       ]
    },
    {
       name: "xyz",
       employees: [
         { name: "number6" },
         { name: "number7" }
       ]
    }
  ]
},{
  org: "xyz"....
}

How to find total employees in "org" by using aggregate? expect result { org: "org", total_employees: 7 }, { org: "xyz", total_employees: x },....

2 Answers 2

4

You can use $size to get length of inner arrays and $reduce to sum those lengths:

db.collection.aggregate([
    {
        $project: {
        total_employees: {
            $reduce: {
                input: "$departments",
                initialValue: 0,
                in: { $add: [ "$$value", { $size: "$$this.employees" } ]  }
            }
        }
        }
    }
])

Mongo playground

Sign up to request clarification or add additional context in comments.

Comments

3

You can find the $size(length) of the array by looping over departments array using $map aggregation and then can $sum together all the array values

db.collection.aggregate([
  { "$project": { 
    "total_employees": {
      "$sum": {
        "$map": { 
          "input": "$departments",
          "in": { "$size": "$$this.employees" }
        }
      }
    }
  }}
])

Output

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "total_employees": 7
  }
]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.