SQL to Aggregation Mapping Chart
https://docs.mongodb.com/manual/reference/sql-aggregation-comparison/
On this page
The aggregation pipeline allows MongoDB to provide native aggregation capabilities that corresponds to many common data aggregation operations in SQL.
The following table provides an overview of common SQL aggregation terms, functions, and concepts and the corresponding MongoDB aggregation operators:
SQL Terms, Functions, and Concepts | MongoDB Aggregation Operators |
---|---|
WHERE | $match |
GROUP BY | $group |
HAVING | $match |
SELECT | $project |
ORDER BY | $sort |
LIMIT | $limit |
SUM() | $sum |
COUNT() | $sum |
join |
New in version 3.2. |
Examples
The following table presents a quick reference of SQL aggregation statements and the corresponding MongoDB statements. The examples in the table assume the following conditions:
The SQL examples assume two tables, orders and order_lineitem that join by theorder_lineitem.order_id and the orders.id columns.
-
The MongoDB examples assume one collection orders that contain documents of the following prototype:
{
cust_id: "abc123",
ord_date: ISODate("2012-11-02T17:04:11.102Z"),
status: 'A',
price: 50,
items: [ { sku: "xxx", qty: 25, price: 1 },
{ sku: "yyy", qty: 25, price: 1 } ]
}
SQL Example | MongoDB Example | Description |
---|---|---|
SELECT COUNT(*) AS count |
db.orders.aggregate( [ |
Count all records from orders |
SELECT SUM(price) AS total |
db.orders.aggregate( [ |
Sum the price field from orders |
SELECT cust_id, |
db.orders.aggregate( [ |
For each unique cust_id, sum theprice field. |
SELECT cust_id, |
db.orders.aggregate( [ |
For each unique cust_id, sum theprice field, results sorted by sum. |
SELECT cust_id, |
db.orders.aggregate( [ |
For each unique cust_id, ord_dategrouping, sum the price field. Excludes the time portion of the date. |
SELECT cust_id, |
db.orders.aggregate( [ |
For cust_id with multiple records, return the cust_id and the corresponding record count. |
SELECT cust_id, |
db.orders.aggregate( [ |
For each unique cust_id, ord_dategrouping, sum the price field and return only where the sum is greater than 250. Excludes the time portion of the date. |
SELECT cust_id, |
db.orders.aggregate( [ |
For each unique cust_id with status A, sum the price field. |
SELECT cust_id, |
db.orders.aggregate( [ |
For each unique cust_id with status A, sum the price field and return only where the sum is greater than 250. |
SELECT cust_id, |
db.orders.aggregate( [ |
For each unique cust_id, sum the corresponding line item qty fields associated with the orders. |
SELECT COUNT(*) |
db.orders.aggregate( [ |
Count the number of distinctcust_id, ord_date groupings. Excludes the time portion of the d |