mongo 聚合索引
-
根据某字段进行分组统计
-
数据源结构
{ "_id" : ObjectId("5fc7694da343baa23c0b2d75"), "id" : 0, "age" : 13, "name" : "name869", "created" : ISODate("2020-12-02T10:15:41.615Z") } { "_id" : ObjectId("5fc7694da343baa23c0b2d76"), "id" : 1, "age" : 101, "name" : "name471", "created" : ISODate("2020-12-02T10:15:41.616Z") } { "_id" : ObjectId("5fc7694da343baa23c0b2d77"), "id" : 2, "age" : 29, "name" : "name115", "created" : ISODate("2020-12-02T10:15:41.616Z") } { "_id" : ObjectId("5fc7694da343baa23c0b2d78"), "id" : 3, "age" : 73, "name" : "name382", "created" : ISODate("2020-12-02T10:15:41.616Z") } { "_id" : ObjectId("5fc7694da343baa23c0b2d79"), "id" : 4, "age" : 1, "name" : "name258", "created" : ISODate("2020-12-02T10:15:41.617Z") } { "_id" : ObjectId("5fc7694da343baa23c0b2d7a"), "id" : 5, "age" : 117, "name" : "name586", "created" : ISODate("2020-12-02T10:15:41.617Z") } { "_id" : ObjectId("5fc7694da343baa23c0b2d7b"), "id" : 6, "age" : 29, "name" : "name15", "created" : ISODate("2020-12-02T10:15:41.618Z") } { "_id" : ObjectId("5fc7694da343baa23c0b2d7c"), "id" : 7, "age" : 55, "name" : "name774", "created" : ISODate("2020-12-02T10:15:41.618Z") } { "_id" : ObjectId("5fc7694da343baa23c0b2d7d"), "id" : 8, "age" : 14, "name" : "name138", "created" : ISODate("2020-12-02T10:15:41.619Z") } { "_id" : ObjectId("5fc7694da343baa23c0b2d7e"), "id" : 9, "age" : 63, "name" : "name920", "created" : ISODate("2020-12-02T10:15:41.619Z") }
-
假设根据
name
进行聚合统计-
查询映射到指定的字段 使用关键字
$project
{"$project":{"name":1}}
-
对
name
字段进行分组,并计算总出现的次数count
{"$group":{"_id":"$name","count":{"$sum":1}}}
-
对已经计算好的次数进行排序 使用关键字
$sort
{"$sort":{"count":-1}} # -1 代表降序 1 代表升序
-
取出前10条记录
{"$limit":10}
-
将以上的步骤都需要放在聚合查询的函数里 关键字
aggregate
db.blog.aggregate( {"$project":{"name":1}}, {"$group":{"_id":"$name","count":{"$sum":1}}}, {"$sort":{"count":-1}}, {"$limit":10} )
-
-