首页 > 解决方案 > 如何获取 mongodb 集合中字段的最常用值的排序列表

问题描述

我有一些类似于以下结构的文件:

{ 
   "name": "item_1",
   "category": ["a", "b"]
},
{ 
   "name": "item_2",
   "category": ["c"]
},
{ 
   "name": "item_3",
   "category": ["a", "c"]
},
{ 
   "name": "item_4",
   "category": ["a"]
},
{ 
   "name": "item_5",
   "category": ["a"]
}

我正在尝试获取集合中所有文档中类别字段最常用值的排序列表。

所以在这个例子中,我期望的返回值应该是这样的:

[
   {
      "category": "a",
      "count": 4
   },
   {
      "category": "c",
      "count": 2
   },
   {
      "category": "b",
      "count": 1
   }
]

有没有办法在猫鼬中进行这样的查询?

标签: node.jsmongodbmongoosemongodb-queryaggregation-framework

解决方案


演示 - https://mongoplayground.net/p/sBpwwvowXLH

使用聚合查询将您的类别$unwind到单独的文档中$group它们按类别返回并获取计数

$总和

db.collection.aggregate({
  "$unwind": "$category"
},
{
  "$group": {
    "_id": "$category",
    count: { $sum: 1 }
  }
})

推荐阅读