SQL to Aggregation Mapping Chart
The aggregation pipeline allowsMongoDB to provide native aggregation capabilities that corresponds tomany common data aggregation operations in SQL.
The following table provides an overview of common SQL aggregationterms, functions, and concepts and the corresponding MongoDBaggregation 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 $sortByCount |
join | $lookup |
SELECT INTO NEW_TABLE | $out |
MERGE INTO TABLE | $merge (Available starting in MongoDB 4.2) |
For a list of all aggregation pipeline and expression operators, seeAggregation Pipeline Quick Reference.
See also
Examples
The following table presents a quick reference of SQL aggregationstatements and the corresponding MongoDB statements. The examples inthe table assume the following conditions:
The SQL examples assume two tables,
orders
andorder_lineitem
that join by theorder_lineitem.order_id
andtheorders.id
columns.The MongoDB examples assume one collection
orders
that containdocuments 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 recordsfrom orders |
|
| Sum the price fieldfrom 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 uniquecust_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 andthe corresponding record count. |
|
| For each unique cust_id , ord_date grouping, sum the price fieldand return only where thesum 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 returnonly where thesum is greater than 250. |
|
| For each unique cust_id ,sum the correspondingline item qty fieldsassociated with theorders. |
|
| Count the number of distinctcust_id , ord_date groupings.Excludes the time portion of the date. |
See also