聚合管道允许MongoDB提供与SQL中的许多常见数据聚合操作相对应的本地聚合功能。
下表概述了常见的SQL聚合术语、函数和概念以及相应的MongoDB聚合操作符:
SQL术语、函数和概念 | MongoDB聚合运算符 |
---|---|
WHERE | $match |
GROUP BY | $group |
HAVING | $match |
SELECT | $project |
ORDER BY | $sort |
LIMIT | $limit |
SUM() | $sum |
COUNT() | |
join | $lookup |
有关所有聚合管道和表达式操作符的列表,请参见聚合管道快速参考。
下表快速引用了SQL聚合语句和相应的MongoDB语句。下表中的例子假设了以下条件:
SQL示例假设两个表orders和order_lineitem,两个表通过order_lineitem.order_id和orders.id联接。
MongoDB示例假设一个集合订单,其中包含以下原型的文档:
SQL 示例 | MongoDB 示例 | 描述 |
---|---|---|
统计 orders 表所有记录数 |
||
汇总 orders 的price 总值 |
||
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. |
原文:https://docs.mongodb.com/manual/reference/sql-aggregation-comparison/