mongodb count num of distinct values per field/key

前端 未结 6 1970
小蘑菇
小蘑菇 2020-11-28 04:18

Is there a query for calculating how many distinct values a field contains in DB.

f.e I have a field for country and there are 8 types of country values (spain, engl

6条回答
  •  忘掉有多难
    2020-11-28 04:49

    Here is example of using aggregation API. To complicate the case we're grouping by case-insensitive words from array property of the document.

    db.articles.aggregate([
        {
            $match: {
                keywords: { $not: {$size: 0} }
            }
        },
        { $unwind: "$keywords" },
        {
            $group: {
                _id: {$toLower: '$keywords'},
                count: { $sum: 1 }
            }
        },
        {
            $match: {
                count: { $gte: 2 }
            }
        },
        { $sort : { count : -1} },
        { $limit : 100 }
    ]);
    

    that give result such as

    { "_id" : "inflammation", "count" : 765 }
    { "_id" : "obesity", "count" : 641 }
    { "_id" : "epidemiology", "count" : 617 }
    { "_id" : "cancer", "count" : 604 }
    { "_id" : "breast cancer", "count" : 596 }
    { "_id" : "apoptosis", "count" : 570 }
    { "_id" : "children", "count" : 487 }
    { "_id" : "depression", "count" : 474 }
    { "_id" : "hiv", "count" : 468 }
    { "_id" : "prognosis", "count" : 428 }
    

提交回复
热议问题