| SQL term |
MongoDB agg framework term |
| WHERE |
$match |
| GROUP BY |
$group |
| SELECT |
$project |
| ORDER BY |
$sort |
 | Note: you can try the agg framework by testing with the v2.1.0 build. Note that 2.1.x is an unstable branch and not for production. Once ready it will be promoted to v2.2. |
MongoDB has a few means of performing aggregation and data processing. In v2.2+ the main means are the aggregation framework and the map/reduce command. In general, if your operation can be expressed in the aggregation framework, use that as it is usually easier than using map/reduce and also performs better.
The table below shows examples of a SQL aggregation statement and the analogous MongoDB agg framework statement. The examples are invocations from the mongo shell, however usage from other programming languages is very similar.
| SQL Statement |
Mongo Statement |
SELECT COUNT(*) FROM users
|
db.users.aggregate([
{ $group: {_id:null, count:{$sum:1}} }
])
|
SELECT SUM(price) FROM orders
|
db.orders.aggregate([
{ $group: {_id:null,
total:{$sum:"$price"} } }
])
|
SELECT cust_id,SUM(price) FROM orders GROUP BY cust_id
|
db.orders.aggregate([
{ $group: {_id:"$cust_id",total:{$sum:"$price"}} }
])
|
SELECT cust_id,SUM(price) FROM orders WHERE active=true GROUP BY cust_id
|
db.orders.aggregate([
{ $match:{active:true} },
{ $group:{_id:"$cust_id",total:{$sum:"$price"}} }
])
|
PLEASE POST QUESTIONS IN THE USER GROUPS FORUM. Post non-question comments and helpful hints here.
blog comments powered by Disqus