Wira Xie
Wira Xie

Reputation: 839

MongoDB, do another count after a group count

I'm kinda new with mongodb. i made a query to count child with same parent (parentid), the query looks like this:

db.Child.aggregate([ { "$group" : { _id:"$parent", count1: { $sum:1 } } } ]) And the result looks like this: enter image description here

The next step i need to do is count how many 1s, 2s, 3s, etc in count1 field above. Is it possible to do another count like that?

Upvotes: 0

Views: 23

Answers (1)

Alex B.
Alex B.

Reputation: 600

If all you're looking to do is get the total number of count1 values, you could add another $group and another accumulator as follows:

db.Child.aggregate([
    { $group: {
        _id: "$parent",
        count1: { $sum: 1 }
    }},
    { $group: {
        _id: "$count1",
        count2: { $sum: 1 }
    }}
])

Upvotes: 1

Related Questions