# MongoDB group()分组
# db.collection.group()
# 前三个是必备参数,“[]”中是可选参数
db.collection.group({ key, reduce, initial [, keyf] [, cond] [, finalize] })
key 可以放用来分组的字段,并且会返回其中字段(group by 后面的字段)
reduce 是在分组操作期间对文档进行操作的聚合函数。可以返回总和或计数。该函数有两个参数:当前文档;该组的聚合结果文档。
initial 对结果中文档,字段进行初始化
cond 对数据筛选的条件,相当于 where
# 示例
db.getCollection('test').group({
key: { 'update_time': 1 },
cond: { update_time: { $gt: '2000-01-01' } },
reduce: function(obj, update_time) { update_time.count++ },
initial: { count: 0 }
})
相当于
select update_time, count(update_time)
from test
where update_time >'2000-01-01'
group by update_time;
# MongoDB 聚合 aggregate()
# db.collection.aggregate([$group{}])
为了便于理解,先将常见的 mongo 的聚合操作和 mysql 的查询做下类比:
SQL 操作/函数 | mongodb 聚合操作 |
---|---|
where | $match |
group by | $group |
having | $match |
select | $project |
order by | $sort |
limit | $limit |
sum() | $sum |
count() | $sum |
join | $lookup(v3.2 新增) |
这边先直说下 $group的语法
# _id字段是必填的;但是,可以指定_id值为null来为整个输入文档计算累计值。
{ $group: { _id: <expression>, <field1>: { <accumulator1> : <expression1> }, ... } }
← 2019-11-13 2019-11-19 →