PastaLover
PastaLover

Reputation: 491

What would be the best way to count demographics from DB? Mongoose+MongoDB

I would like to present in my application's admin-pannel a count of the users demographics.

For example:

United States: 500 users

United Kingdom: 241 users

India: 2141241221 users.

Israel: 1 user.

Since there are a lot of countries in the world, I don't want to start searching for each country specifically. I would like to run one search that will count how many times each country appeared. I can't think of an idea that would not require me to search for countries specifically.

Example of what I do NOT want to do:

mongoose.find({Country: India}).then((documents) => { console.log("documents.length")} )

Using this method will require me to write the same line for each country that exists, and I'm sure theres a better way to go about it.

Upvotes: 0

Views: 96

Answers (1)

Himanshu
Himanshu

Reputation: 949

Use Mongodb Aggregation $group stage to achieve this.

Upvotes: 0

Related Questions