[英]mongodb - get top items from a collection based on its usage count as a field in another collection
如何根据它们作为另一个集合项目中的字段的用途来获取排名靠前的项目列表?
这是一个解释场景的 mongodb playground - https://mongoplayground.net/p/gTMm1JVv9uV
在下面的示例中, category 245
在posts
集合中使用了两次,类别276
使用了一次。 output 将根据posts
中的使用次数对类别进行排名
请注意,帖子集合只有类别 ID,因此需要查找类别集合。
基于此,预期的 output 是类别文本的数组。
{
topCategories: ["category 245", "category 276"]
}
两个 collections 中的示例数据如下:
db={
categories: [
{
"_id": 231,
"text": "category 231",
},
{
"_id": 245,
"text": "category 245",
},
{
"_id": 276,
"text": "category 276",
}
],
posts: [
{
"_id": 71,
category: "245"
},
{
"_id": 72,
category: "276"
},
{
"_id": 74,
category: "245"
}
]
}
我在之前的查询中使用addToSet
,但发现它不维护顺序。 我已将其替换为push
运算符。
db.posts.aggregate([
{
$addFields: {
category: {
$toInt: "$category"
},
}
},
{
$lookup: {
from: "categories",
as: "category",
localField: "category",
foreignField: "_id"
}
},
{
"$unwind": "$category"
},
{
"$group": {
"_id": "$category._id",
"count": {
"$sum": 1
},
"category": {
"$first": "$category"
}
}
},
{
"$sort": {
"count": -1
}
},
{
"$project": {
categoriesText: "$category.text"
}
},
{
"$group": {
"_id": null,
"categoriesText": {
"$push": "$categoriesText"
}
}
},
{
"$project": {
_id: 0,
topCategories: "$categoriesText"
}
}
])
你可以试试,
$group
by category
并使用 $toInt 转换为 integer,使用$toInt
获取 count 中重复类别的$sum
$loopup
与类别集合$sort
按计数字段降序排序$group
by null 用于在数组字段中组合类别,使用$arrayElemAt
从类别数组中获取第一个元素并将其推topCategories
字段中db.posts.aggregate([
{
$group: {
_id: { $toInt: "$category" },
count: { $sum: 1 }
}
},
{
$lookup: {
from: "categories",
as: "category",
localField: "_id",
foreignField: "_id"
}
},
{ $sort: { count: -1 } },
{
$group: {
_id: null,
topCategories: {
$push: { $arrayElemAt: ["$category.text", 0] }
}
}
}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.