Most common distinct values mongodb

一笑奈何 提交于 2019-12-04 08:24:33

2017-08-01 Update

As release of MongoDB 3.4, the following code can be simplified by using $sortByCount, which essentially equals to $group + $sort. Code snippet:

col.aggregate([{
    "$sortByCount": "$name"
}], ...);

The mongodb aggregation framework would do the job. Code sample:

var MongoClient = require("mongodb").MongoClient;
MongoClient.connect("mongodb://localhost/YourDB", function(err, db) {
    var col = db.collection("YourCol");
    col.aggregate([{
        "$group": {_id: "$name", count: { "$sum": 1}}
    }, {
        "$sort": {count: -1}
    }], function(err, docs) {
        var keys = []
        docs.forEach(function(doc) {
            console.log(JSON.stringify(doc)); // do what you want here.
        });
    });
});

The aggregation framework uses different "filters" to filter out the result set. As you can see in the sample, there's an array of all these filters.
Here I have 2 filters, the first one:

{"$group": {_id: "$name", count: { "$sum": 1}}}

is to group your data by name and count the repeated times.
The 2nd one:

{"$sort": {count: -1}}

is to sort the result by repeated times (count).
if you want only the max repeated one record, you can add a filter there:

{"$limit": 1}

You can do a lot more things with the framework. refer to the doc about operators

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!