node.js - 如何获取 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
}
]
有没有办法在猫鼬中进行这样的查询?
解决方案
演示 - https://mongoplayground.net/p/sBpwwvowXLH
使用聚合查询将您的类别$unwind到单独的文档中$group它们按类别返回并获取计数
db.collection.aggregate({
"$unwind": "$category"
},
{
"$group": {
"_id": "$category",
count: { $sum: 1 }
}
})
推荐阅读
- spring-boot - 无法完成请求:java.io.IOException: Stream closed from Spring boot Controller method
- python - Pandas 使用字典键值增量更新/向行添加列
- jenkins - 在共享的 groovy 脚本中调用 timeout() 和 input()
- android - 在 Android 中使用全局线程池或仅劫持一个用于异步任务
- pandas - 具有不同顺序的数据框行,如何根据规则对所有行进行排序?
- python - 在 SQL Alchemy 中加入多个表后如何进行 GROUP BY
- javascript - 未捕获的类型错误:无法在 var 数据上设置 null 属性“innnerHTML”
- html - Adding formControlName makes the default value disappear in my form's dropdown in Angular
- arrays - 为什么 PowerShell 会自动展平数组?
- android - 如何制作负载回收器适配器以使其快速