Hi, Can anybody told me the Equivalent MongoDB query for the following RDBMS sql query

64 views
Skip to first unread message

Aditya Kumar

unread,
Sep 19, 2017, 8:46:21 AM9/19/17
to mongodb-user
I have searched a lot in interent to find out the MongoDB code for the following SQL query. Can anybody help me out with this

SELECT country, count(*) as total_employees, sum(salary) as total_sal
FROM employee
group by country 
having avg(salary) >= 10000;

Please don't tell me with db.employee.group() function because it's now deprecated. Looking for solution with db.employee.aggregate() function.

Rhys Campbell

unread,
Sep 20, 2017, 6:08:45 AM9/20/17
to mongodb-user
Try this;

db.employee.aggregate([
{ "$group": { "_id": "$country", "total_employees": { "$sum": 1 }, "total_sal": { "$sum": "$salary" }, "avg_sal": { "$avg": "$salary" } }},
{ "$match":  { "avg_sal": { "$gt": 10000 } } }
]);

It's always worth providing a few example documents. You might get a quicker answer.

Rhys


sourav biswas

unread,
Sep 20, 2017, 6:29:05 PM9/20/17
to mongodb-user
also do double grouping in mongodb if there is a need to do something like count (distinct <field>)
Reply all
Reply to author
Forward
0 new messages