m1l05z
m1l05z

Reputation: 378

mongodb group by first character

I have a problem in mongodb.

I want to create aggregation witch result will be like this:

A 10
B 2
C 4
D 9
E 3
...

I have a column words in my table and I want to group my records according to first character of column words.

I find resolve for sql but not for mongo.

I will be very grateful for your help

Upvotes: 2

Views: 4654

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

You don't show what the docs in your collection look like, but you can use the aggregate collection method to do this:

// Group by the first letter of the 'words' field of each doc in the 'test'
// collection while generating a count of the docs in each group.
db.test.aggregate({$group: {_id: {$substr: ['$words', 0, 1]}, count: {$sum: 1}}})

Upvotes: 10

Related Questions