Skip to main content

Aggregation

CORMO supports some basic aggregation operations via Query#group.

DescriptionCORMOSQLMongoDB
Count allOrder.group(null, { count: { $sum: 1 } })SELECT COUNT(*) AS count
FROM orders
db.orders.aggregate([
  {$group:{_id:null,count:{$sum:1}}}
])
Sum allOrder.group(null, { total: { $sum: '$price' } })SELECT SUM(price) AS total
FROM orders
db.orders.aggregate([
  {$group:{_id:null,total:{$sum:'$price'}}}
])
Only for filtered recordsOrder.where({ price: { $lt: 10 } })
.group(null, { count: { $sum: 1 }, total: { $sum: '$price' } })
SELECT COUNT(*) AS count, SUM(price) AS total
FROM orders
WHERE price<10
db.orders.aggregate([
  {$match:{price:{$lt:10}}},
  {$group:{_id:null,count:{$sum:1},total:{$sum:'$price'}}}
])
GroupingOrder.group('customer', { count: { $sum: 1 }, total: { $sum: '$price' } })SELECT customer, COUNT(*) AS count, SUM(price) AS total
FROM orders
GROUP BY customer
db.orders.aggregate([
  {$group:{_id:'$customer',count:{$sum:1},total:{$sum:'$price'}}}
])
Sort by group columnOrder.group('customer', { total: { $sum: '$price' } })
.order('customer')
SELECT customer, SUM(price) AS total
FROM orders
GROUP BY customer
ORDER BY customer
db.orders.aggregate([
  {$group:{_id:'$customer',total:{$sum:'$price'}}},
  {$sort:{_id:1}}
])
Sort by aggregated columnOrder.group('customer', { total: { $sum: '$price' } })
.order('total')
SELECT customer, SUM(price) AS total
FROM orders
GROUP BY customer
ORDER BY total
db.orders.aggregate([
  {$group:{_id:'$customer',total:{$sum:'$price'}}},
  {$sort:{total:1}}
])
Condition on aggregated columnOrder.group('customer', { count: { $sum: 1 } })
.where({ count: { $gte: 3 } })
SELECT customer, COUNT(*) AS count
FROM orders
GROUP BY customer
HAVING count>=3
db.orders.aggregate([
  {$group:{_id:'$customer',count:{$sum:1}}},
  {$match:{count:{$gte:3}}}
])
Grouping by multiple columnsOrder.group('customer date', { count: { $sum: 1 } })SELECT customer, date, COUNT(*) AS count
FROM orders
GROUP BY customer, date
db.orders.aggregate([
  {$group:{_id:{customer:'$customer', date:'$date'},count:{$sum:1}}}
])
Min/Max functionsOrder.group('customer', { min_price: { $min: '$price' }, max_price: { $max: '$price' } })SELECT customer, MIN(price) AS min_price, MAX(price) AS max_price
FROM orders
GROUP BY customer
db.orders.aggregate([
  {$group:{_id:'$customer',min_price:{$min:'$price'},max_price:{$max:'$price'}}}
])