Mongo distinct 查询

1. 使用 distinct 语句

db.member.distinct("phone");

此语句会列出 member 表所有数据去重后的 phone 的值,如下所示:

/* 1 */
[
    "13011111111",
    "",
    "13012341234",
    "13922222222",
    "15056785678",
    "15099999999",
    null
]

要获取去重后的数量,可用如下语句:

db.member.distinct("phone").length;

得到的结果

7

注意: mongo distinct 查询结果集大于16M 时会查询失败,失败信息如下: 
{“message” : “distinct failed: MongoError: distinct too big, 16mb cap”,”stack” : “script:1:20”}

2. 使用聚合

db.member.aggregate([
    {$group: {_id: "$phone", count: {$sum: 1}}},
]);

此语句会列出 phone 字段的所有值并给出每个值出现的次数:

 

 

你可能感兴趣的:(DB)