a4xrbj1
a4xrbj1

Reputation: 425

MongoDB: How can I get a count of a field in a collection grouped by first character and matching a 2nd field?

Following this question's answer (https://stackoverflow.com/a/20817040/2656506) I was able to group a field based on it's first character with this command:

db.kits.aggregate({ $group: {_id: {$substr: ['$kit', 0, 1]}, count: {$sum: 1}}})

But I can't figure out how I can additionally group only those documents which match an additional condition like _id: 'abc' in the same query. Can it be done in one query?

Thanks in advance!

Upvotes: 0

Views: 56

Answers (1)

TomG
TomG

Reputation: 2529

add $match pipeline stage to your aggregation query:

db.kits.aggregate(
    [
        {
            $match: {
                _id: 'abc'
            }
        },
        {
            $group: {
                _id: {
                    $substr: ['$kit', 0, 1]
                },
                count: {$sum: 1}
            }
        }
    ]
)

Upvotes: 2

Related Questions