MongoDB number of records

How to get the number of records (in the collection) that contain only unique data in a certain key?

For instance:

{
   "_id": ObjectId("4f9d996eba6a7aa62b0005ed"),
   "tag": "web" 
}
{
   "_id": ObjectId("4f9d996eba6a7aa62b0006ed"),
   "tag": "net" 
}
{
   "_id": ObjectId("4f9d996eba6a7aa62b0007ed"),
   "tag": "web" 
}
{
   "_id": ObjectId("4f9d996eba6a7aa62b0008ed"),
   "tag": "page" 
}

The number of entries with a unique key "tag" and return 3.

ps: if possible, how to get a list of all found unique key values: "tag"?

+3
source share
2 answers

To get a list unique, you need either DISTINCT, or GROUP BY. MongoDB supports both paradigms:

To get a list of all the different values tagthat you ran:

db.mycollection.distinct('tag');

or

db.runCommand({ distinct: 'mycollection', key: 'tag' })

and you can get the score simply by looking at the lengthresult:

db.mycollection.distinct('tag').length

Note on the command DISTINCTfrom the documentation:Note: the distinct command results are returned as a single BSON object. If the results could be large (> max document size – 4/16MB ), use map/reduce instead

+2

Map/Reduct .

"content" 4 ( ). , map/reduce, . "".

var map = function() {
    emit(this.tag, 1);
};

var reduce = function(key,values){
    var result = 0;
    for(v in values){
        result += values[v];
    }
    return result;
};

res = db.content.mapReduce(map,reduce,{out:"result"}});

.

{ "_id" : "net", "value" : 1 }
{ "_id" : "page", "value" : 1 }
{ "_id" : "web", "value" : 2 }
+2

All Articles