// 表结构如下
db.getCollection('user').find({})
/* 1 */
{
"_id" : ObjectId("60cff68f178109181220769e"),
"name" : "张三",
"age" : 17.0,
"sex" : "man"
}
/* 2 */
{
"_id" : ObjectId("60cff6b4178109181220769f"),
"name" : "张三",
"age" : 18.0,
"sex" : "man"
}
/* 3 */
{
"_id" : ObjectId("60cff6df17810918122076a0"),
"name" : "李四",
"age" : 18.0,
"sex" : "man"
}
/* 4 */
{
"_id" : ObjectId("60cff6f017810918122076a1"),
"name" : "王五",
"age" : 18.0,
"sex" : "woman"
}
// 求 不同的性别里去掉重名的名字有多少人
//1.使用distinct,但是在数据量特别大的情况(结果集大于16M)查询失败,失败信息如下:
{“message” : “distinct failed: MongoError: distinct too big, 16mb cap”,”stack” : “script:1:20”}
//在海量数据的时候可以考虑多次分组查询,这种情况不会出现使用distinct的报错场景,在内存消耗和查询效率都比较好
db.getCollection('user').aggregate([
{$group: {_id:{sex:"$sex",name:"$name"}}},
{$group: {_id:{sex:"$_id.sex"},count:{$sum:1}}}
])
//如果加上查询条件就是如下:
db.getCollection('user').aggregate([
{$match:{"sex" : "man"}},
{$group: {_id:{sex:"$sex",name:"$name"}}},
{$group: {_id:{sex:"$_id.sex"},count:{$sum:1}}}
])