【发布时间】:2020-02-28 21:16:47
【问题描述】:
我使用 mongodb 和 mongoose 从 nodejs 连接。 我的关键词集:
keywords
{
_id: { type: Schema.Types.ObjectId },
word: { type: String, index: true },
rank: {type: Number}, // Rank is count of voting from users.
source: {type: String},
link: {type: Schema.Types.ObjectId, ref: 'Content'} // Link to contents collection
}
和内容合集
{
_id: { type: Schema.Types.ObjectId },
title: { type: String },
content: { type: String }
}
我的想法:
- 第一步:使用全文搜索查找匹配的关键词,排序 最接近的匹配,排名(按最接近的匹配分组)
- 第二步:获取链接(关键字的链接属性)查找内容$in 链接。
但在第 1 步排序时并不完全正确。
我的代码:
// Get keywords
let indexes = await Keyword.aggregate([
{ $match: {
$text: { $search: 'request query' }
}},
{ $limit: 100 },
{ $sort: { rank: -1, createdAt: -1 } }, // I want to sort by highest rank
{ $group: { _id: '$link' } },
{ $project: { link: 1 } }
]);
return await Content.find({
_id: {
$in: indexes.map((item) => {
return item._id;
})
}
});
任何可以帮助我的想法。非常感谢!
【问题讨论】: