1

I'm making an aggregation and I'm at a step where I have the following:

˅ typeCount: Array
    ˅ 0: Object
        _id: "System"
        count: 1002
    ˅ 1: Object
        _id: "Application"
        count: 3065
˅ affectedComputers: Array
    ˅ 0: Object
        _id: ObjectId('...')
        count: 1
    ˅ 1: Object
        _id: ObjectId('...')
        count: 1
    ...

Now I'm trying to get the following result:

application: 3065
system: 1002
affectedComputers: 2951

The affectedComputers array is a group by computers, so I just use $size to get the count of computers. But I don't know how to get the Application and System count... And keep in mind that they can also be 0 if there is no instances when I group.

I've done the following:

{ 
    $project {
        'affectedComputers': { $size: '$affectedComputers'}
    }
}

This only gives me the affected computers count, how do I get the System and Application count if there are any, if not then get it as 0?

1 Answer 1

2

Easiest way to do this generically is just to use $arrayToObject and convert the whole array, You can also define it manually field by field, here's how to do the first approach:

db.collection.aggregate([
  {
    $replaceRoot: {
      newRoot: {
        $mergeObjects: [
          {
            "affectedComputers": {
              $size: "$affectedComputers"
            }
          },
          {
            "$arrayToObject": {
              $map: {
                input: "$typeCount",
                in: {
                  k: "$$this._id",
                  v: "$$this.count"
                }
              }
            }
          }
        ]
      }
    }
  }
])

Mongo Playground

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

2 Comments

Okay, this is a good solution but there is two small issues with it. First thing is that it uses the this._id directly as key, which is a problem because I want the key to be in lowercase. Second thing is that if there is no system object in the array, it doesn't return the system field, in the end result. it should still return system: 0. This is why I figured that manually defining would be easier?
Regarding the lowercase you can just add $toLower, but yes you'll need to manually define the fields if you want to get 0 counts

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.