Mongo DB - Count of nested/embedded document keys

Viewed 84

I'm trying to find a count embedded document keys across documents in a collection. For example:

doc1 = {
  field1: 'foo',
  field2: {
    12322 = {
      ...
    },
    244 = {
      ...
    },
    8791 = {
      ...
    }
  }
}

doc2 = {
  field1: 'bar',
  field2: {
    789 = {
      ...
    },
    244 = {
      ...
    },
    8791 = {
      ...
    },
    12 = {
      ...
    }
  }
}

I'd like to run an aggregation where I can get the count of these keys.

Result

{
  12: 1,
  244: 2.
  789: 1,
  8791: 2,
  12322: 1
}

Bonus: one of the fields in each of those embedded docs is a date field, I'm eventually going to need to filter out objects that are older than a certain date.

1 Answers

You can do with aggregation

  • $objectToArray to make the object as key-value pair array
  • $unwind to deconstruct the array
  • $group to count the sum of each key, next group to rearrange key-value pair for $arrayToObjet
  • $replaceRoot to make this to root

Here is the code

db.collection.aggregate([
  { $project: { data: { "$objectToArray": "$field2" } }},
  { "$unwind": "$data" },
  {
    "$group": {
      "_id": "$data.k",
      "count": { "$sum": 1 }
    }
  },
  {
    "$group": {
      "_id": null,
      "data": { "$push": { k: "$_id", v: "$count" } }
    }
  },
  {  $project: { data: { "$arrayToObject": "$data" } } },
  { "$replaceRoot": { "newRoot": "$data" } }
])

Working Mongo playground

Related