$group
集合 sales 内容如下:
db.sales.insert([{ "_id" : 1, "item" : "abc", "price" : 10, "quantity" : 2, "date" : ISODate("2014-03-01T08:00:00Z") },{ "_id" : 2, "item" : "jkl", "price" : 20, "quantity" : 1, "date" : ISODate("2014-03-01T09:00:00Z") },{ "_id" : 3, "item" : "xyz", "price" : 5, "quantity" : 10, "date" : ISODate("2014-03-15T09:00:00Z") },{ "_id" : 4, "item" : "xyz", "price" : 5, "quantity" : 20, "date" : ISODate("2014-04-04T11:21:39.736Z") },{ "_id" : 5, "item" : "abc", "price" : 10, "quantity" : 10, "date" : ISODate("2014-04-04T21:23:13.331Z") }])
Group by Month, Day, and Year
下面的聚合操作使用 $group 将文档按月、日、年组分组, 计算平均数量以及每个组的文档数:
该操作返回以下结果:
{ "_id" : { "month" : 4, "day" : 4, "year" : 2014 }, "averageQuantity" : 15, "count" : 2 }
Group by null
db.sales.aggregate(
[
{
$group : {
_id : null,
totalPrice: { $sum: { $multiply: [ "$price", "$quantity" ] } },
count: { $sum: 1 }
}
}
)
该操作返回以下结果:
检索不同的值 (类似sql Distinct)
下面的聚合操作使用 $group 将item字段去重,以检索不同的项目值:
db.sales.aggregate( [ { $group : { _id : "$item" } } ] )
该操作返回以下结果:
{ "_id" : "xyz" }
{ "_id" : "jkl" }
类似sql语句: select _id from sales group by _id
透视数据
db.books.insert([{ "_id" : 8751, "title" : "The Banquet", "author" : "Dante", "copies" : 2 },{ "_id" : 8752, "title" : "Divine Comedy", "author" : "Dante", "copies" : 1 },{ "_id" : 8645, "title" : "Eclogues", "author" : "Dante", "copies" : 2 },{ "_id" : 7000, "title" : "The Odyssey", "author" : "Homer", "copies" : 10 },{ "_id" : 7020, "title" : "Iliad", "author" : "Homer", "copies" : 10 },])
Group title by author
下面的聚合操作 按authors分组, 收集books中的titles
该操作返回以下结果:
{ "_id" : "Homer", "books" : [ "The Odyssey", "Iliad" ] }
{ "_id" : "Dante", "books" : [ "The Banquet", "Divine Comedy", "Eclogues" ] }
Group Documents by author
下面的聚合操作 按author分组,收集 $$ROOT 系统变量(代表文档自身)
db.books.aggregate(
[
{ $group : { _id : "$author", books: { $push: "$$ROOT" } } }
)