$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 将文档按月、日、年组分组, 计算平均数量以及每个组的文档数:

    该操作返回以下结果:

    1. { "_id" : { "month" : 4, "day" : 4, "year" : 2014 }, "averageQuantity" : 15, "count" : 2 }

    Group by null

    1. db.sales.aggregate(
    2. [
    3. {
    4. $group : {
    5. _id : null,
    6. totalPrice: { $sum: { $multiply: [ "$price", "$quantity" ] } },
    7. count: { $sum: 1 }
    8. }
    9. }
    10. )

    该操作返回以下结果:

    检索不同的值 (类似sql Distinct)

    下面的聚合操作使用 $group 将item字段去重,以检索不同的项目值:

    1. db.sales.aggregate( [ { $group : { _id : "$item" } } ] )

    该操作返回以下结果:

    1. { "_id" : "xyz" }
    2. { "_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

    该操作返回以下结果:

    1. { "_id" : "Homer", "books" : [ "The Odyssey", "Iliad" ] }
    2. { "_id" : "Dante", "books" : [ "The Banquet", "Divine Comedy", "Eclogues" ] }

    Group Documents by author

    下面的聚合操作 按author分组,收集 $$ROOT 系统变量(代表文档自身)

    1. db.books.aggregate(
    2. [
    3. { $group : { _id : "$author", books: { $push: "$$ROOT" } } }
    4. )

    SQL VS Aggregation 区别