DEV Community

Tell Me How
Tell Me How

Posted on

Transform SQL Query into MongoDB Query

You can run SQL SELECT Query against MongoDB. SQL support includes functions, expressions, aggregation for collections with nested objects and arrays.

Let's look at how to use the GROUP BY clause with the SUM function in SQL.

Instead of writing the MongoDB query which is represented as a JSON-like structure

db.employees.aggregate([
  {
   $group:  {
   _id:  "$department",
   total:  { $sum:  "$salary"  }
    },
    }
])

You can query MongoDB by using old SQL which you probably already know

SELECT department, SUM(salary) AS total FROM employees GROUP BY department

Please note that SQL features are not natively supported by MongoDB. The SQL query is validated and translated into a MongoDB query and executed by MongoBooster. The Equivalent MongoDB Query can be viewed in console.log tab.

Group By:

View equivalent MongoDB Query:

If you’re not familiar with NoSQLBooster for MongoDB, it is a shell-centric cross-platform GUI tool for MongoDB which provides fluent query builder, SQL query, update-in-place, ES2017 syntax support and true intellisense experience.

Top comments (0)