Search code examples
mongodbmongodb-queryaggregateaggregation

How to get value from objects in array of objects?


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?


Solution

  • 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