The aggregation pipeline allows MongoDB to provide native aggregation capabilities that corresponds to many common data aggregation operations in SQL.聚合管道允许MongoDB提供与SQL中许多常见数据聚合操作相对应的本机聚合功能。
The following table provides an overview of common SQL aggregation terms, functions, and concepts and the corresponding MongoDB aggregation operators:下表概述了常见的SQL聚合术语、函数和概念以及相应的MongoDB聚合运算符:
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 |
UNION ALL | $unionWith |
For a list of all aggregation pipeline and expression operators, see:有关所有聚合管道和表达式运算符的列表,请参阅:
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:下表提供了SQL聚合语句和相应MongoDB语句的快速参考。表中的示例假设了以下条件:
The SQL examples assume two tables,SQL示例假设有两个表,ordersandorder_lineitemthat join by theorder_lineitem.order_idand theorders.idcolumns.orders和order_lineitem,它们通过order_linetemorder_id和ordersid列连接。The MongoDB examples assume one collectionMongoDB示例假设一个集合ordersthat contain documents of the following prototype:orders包含以下原型的文档:{
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 } ]
}
|
| ordersorders中的所有记录 |
|
| price field from ordersorders中的price字段求和 |
|
| cust_id, sum the price field.cust_id,将price字段相加。 |
|
| cust_id, sum the price field, results sorted by sum.cust_id,将price字段相加,结果按总和排序。 |
|
| cust_id, ord_date grouping, sum the price field. Excludes the time portion of the date.cust_id、ord_date分组,将price字段相加。不包括日期的时间部分。 |
|
| cust_id with multiple records, return the cust_id and the corresponding record count.cust_id,返回cust_id和相应的记录计数。 |
|
| 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.cust_id、ord_date分组,将price字段相加,仅在总和大于250时返回。不包括日期的时间部分。 |
|
| cust_id with status A, sum the price field.A的唯一cust_id,将price字段相加。 |
|
| cust_id with status A, sum the price field and return only where the sum is greater than 250.A的每个唯一cust_id,将price字段相加,仅在总和大于250时返回。 |
|
| cust_id, sum the corresponding line item qty fields associated with the orders.cust_id,将与订单关联的相应行项目qty字段相加。 |
|
| cust_id, ord_date groupings. Excludes the time portion of the date.cust_id、ord_date分组的数量。不包括日期的时间部分。 |