DEV Community

Tell Me How
Tell Me How

Posted on

3 3

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"  }
    },
    }
])
Enter fullscreen mode Exit fullscreen mode

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

SELECT department, SUM(salary) AS total FROM employees GROUP BY department
Enter fullscreen mode Exit fullscreen mode

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay