【发布时间】:2021-10-01 01:14:18
【问题描述】:
这是我尝试过的一个 mongodb 游乐场 - https://mongoplayground.net/p/_rjZo8aak6b
在此示例中,我在 Array 中按顺序获取顶级类别,但我还需要包含出现次数的对象数组。
在下面的示例中,类别 245 在帖子集合中使用了两次,而 276 则使用了一次。输出将根据帖子中的使用次数对类别进行排名
请注意,帖子集合只有类别 ID,因此需要查找类别集合。
预期结果是:
{
topCategories: [{name: "category 245", count: 2},{name: "category 276", count: 1}]
}
样本数据如下:
db={
categories: [
{
"_id": 231,
"text": "category 231"
},
{
"_id": 276,
"text": "category 276"
},
{
"_id": 245,
"text": "category 245"
}
],
posts: [
{
"_id": 74,
category: "245"
},
{
"_id": 75,
category: "245"
},
{
"_id": 72,
category: "276"
}
]
}
注意:这个问题与 mongodb - get top items from a collection based on its usage count as a field in another collection 所以请不要标记是重复的。
【问题讨论】:
标签: mongodb mongoose aggregation-framework aggregate aggregate-functions