本文翻译自:https://docs.mongodb.com/manual/reference/sql-aggregation-comparison/
由于本人也在学习Mongodb,项目中用到聚合,看到文档这篇不错就翻译一下(仅供参考)
SQL中的聚合函数和Mongodb中的管道相互对应的关系:
WHERE $match GROUP BY $group HAVING $match SELECT $project ORDER BY $sort LIMIT $limit SUM() $sum COUNT() $sum join $lookup
例子:
先创建文档,填充数据
/* 0 */ { "_id" : ObjectId("5812b447311bb4272016496a"), "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 }] } /* 1 */ { "_id" : ObjectId("58131494311bb418b058fcba"), "cust_id" : "a", "ord_date" : ISODate("2012-11-02T17:04:11.102Z"), "status" : "B", "price" : 70, "items" : [{ "sku" : "xxx", "qty" : 25, "price" : 1 }, { "sku" : "yyy", "qty" : 25, "price" : 1 }] } /* 2 */ { "_id" : ObjectId("581314b6311bb418b058fcbb"), "cust_id" : "ab", "ord_date" : ISODate("2012-11-02T17:04:11.102Z"), "status" : "E", "price" : 60, "items" : [{ "sku" : "xxx", "qty" : 55, "price" : 1 }, { "sku" : "yyy", "qty" : 25, "price" : 1 }] }
例1:
SQL:
SELECT COUNT(*) AS count FROM orders
Mongodb:
db.orders.aggregate([ { $group:{ _id:null, count:{$sum:1} } } ])
例2:
SQL:
SELECT SUM(price) AS total FROM orders
Mongodb:
db.orders.aggregate( [ { $group: { _id:null, total:{$sum:"$price"} } } ])
例3:
SQL:
SELECT cust_id,SUM(price) AS total FROM orders GROUP BY cust_id
Mongodb:
db.orders.aggregate([ { $group: { _id:"$cust_id", total: { $sum:"$price" } } }, { $sort: { total:1 } } ])
例4:
SQL:
SELECT cust_id, ord_date,SUM(price) AS total FROM orders GROUP BY cust_id, ord_date
Mongodb:
db.orders.aggregate([ { $group: { _id: { cust_id:"$cust_id", ord_date: { month:{$month:"$ord_date"}, day:{$dayOfMonth:"$ord_date"}, year:{$year:"$ord_date"} } }, total:{$sum:"$price"} } } ])
时间: 2024-12-23 13:22:29