SQL to Aggregation Mapping Chart
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 | |
GROUP BY | |
HAVING | |
SELECT | |
ORDER BY | |
LIMIT | |
SUM() | |
COUNT() | |
join | |
SELECT INTO NEW_TABLE | |
MERGE INTO TABLE | $merge (Available starting in MongoDB 4.2) |
UNION ALL | $unionWith (Available starting in MongoDB 4.4) |
For a list of all aggregation pipeline and expression operators, see Aggregation Pipeline Quick Reference.
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
andorder_lineitem
that join by theorder_lineitem.order_id
and theorders.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 | ||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
| Count all records
from orders | ||||||||||||||||||||||||||
|
| Sum the price field
from orders | ||||||||||||||||||||||||||
|
| For each unique cust_id ,
sum the price field. | ||||||||||||||||||||||||||
|
| For each unique cust_id ,
sum the price field,
results sorted by sum. | ||||||||||||||||||||||||||
|
| For each unique
cust_id , ord_date grouping,
sum the price field.
Excludes the time portion of the date. | ||||||||||||||||||||||||||
|
| For cust_id with multiple records,
return the cust_id and
the corresponding record count. | ||||||||||||||||||||||||||
|
| For each unique cust_id , ord_date
grouping, sum the price field
and return only where the
sum is greater than 250.
Excludes the time portion of the date. | ||||||||||||||||||||||||||
|
| For each unique cust_id
with status A ,
sum the price field. | ||||||||||||||||||||||||||
|
| For each unique cust_id
with status A ,
sum the price field and return
only where the
sum is greater than 250. | ||||||||||||||||||||||||||
|
| For each unique cust_id ,
sum the corresponding
line item qty fields
associated with the
orders. | ||||||||||||||||||||||||||
|
| Count the number of distinct
cust_id , ord_date groupings.
Excludes the time portion of the date. |