mongodb distinct 的使用,以及如何计算distinct后的count值

db.runCommand({"distinct":"accesslog","key":"deviceId","query":{"time":/^2011-12-15/}}).values.length();

相当于sql:

select count(deviceId) from (select distinct deviceId  from accesslog where time like "2011-12-15%") ;

解释:

查询2011-12-15日,deviceId不同的总数。


"distinct":查询的表或collection;
"key":根据哪个字段排重
"query":查询条件,如果要用类似于sql中的like,则字段名字后的值要用正则匹配,例如/^2011-12-15/ 相当于 like "2011-12-15%"

db.runCommand({"distinct":"accesslog","key":"deviceId"})

结果:

{
        "values" : [
                "357194042155846",
                "9530283B-3FCE-4A07-B939-8E03B5AD17DF",
                "D7D2C00D-A2ED-4E64-B9B7-C2BEB7CE863E",
        ],
        "stats" : {
                "n" : 323,
                "nscanned" : 3223,
                "nscannedObjects" : 3223,
                "timems" : 5
        },
        "ok" : 1
}

db.runCommand({"distinct":"accesslog","key":"deviceId","query":{"time":/^2011-12-15/}}).values.length();

结果:
3

你可能感兴趣的:(distinct)