user3142695
user3142695

Reputation: 17362

aggregation to get a counting list

How do I get a counting list for all chapter codes for this data?

[
    {
        catId: 101,
        chapter: [
            {
                id: '1234',
                title: 'Title 1',
                code: 'X12.3'
            },
            {
                id: 'abcd',
                title: 'Title 2',
                code: 'X12.4'
            }
        ]
    },
    {
        catId: 102,
        chapter: [
            {
                id: 'abcd',
                title: 'Title 2',
                code: 'X12.4'
            }
        ]
    }
]

For this simple example I would expect something like

2 - X12.4
1 - X12.3

I think I need an aggregation like:

db.collection.aggregate([
  {},
  {
    $group: {
      _id: '$code',
      Datasets: { $sum: 1 }
    }
  }
])

Upvotes: 1

Views: 24

Answers (1)

SuleymanSah
SuleymanSah

Reputation: 17888

Before grouping, you first need to $unwind the chapter array.

db.collection.aggregate([
  {
    $unwind: "$chapter"
  },
  {
    $group: {
      _id: "$chapter.code",
      count: {
        $sum: 1
      }
    }
  }
])

This will give the following result:

[
  {
    "_id": "X12.4",
    "count": 2
  },
  {
    "_id": "X12.3",
    "count": 1
  }
]

Playground

Upvotes: 1

Related Questions