【发布时间】:2022-09-30 23:49:35
【问题描述】:
这是完整的查询:
async getHistoryByTag(context: StandardContext) {
const { mongo } = context.state;
const tag = context.params.tag.replace(/-+/g, \" \");
const today = new Date();
const prevSunday = getOneWeekAgo(today);
console.log(\"today: \", today, \"prev sunday: \", prevSunday);
const all = await mongo
.collection(\"search_history\")
.aggregate<SearchHistoryModel & { username: string; word: string }>([
{
$match: {
created_at: { $gt: prevSunday.toISOString() },
},
},
{
$lookup: {
from: \"users\",
localField: \"user_id\",
foreignField: \"id\",
as: \"user\",
pipeline: [
{
$project: {
username: 1,
},
},
],
},
},
// { search_id: 1, created_at: 1, url: 1 }
{
$lookup: {
from: \"positive\",
localField: \"search_id\",
foreignField: \"search_id\",
as: \"positive\",
pipeline: [
{
$project: {
word: 1,
},
},
],
},
},
{
$unwind: {
path: \"$user\",
preserveNullAndEmptyArrays: true,
},
},
{
$unwind: {
path: \"$positive\",
preserveNullAndEmptyArrays: true,
},
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: [\"$$ROOT\", \"$user\", \"$positive\"],
},
},
},
{
$match: {
word: tag,
},
},
{
$project: {
user: 0,
positive: 0,
},
},
{
$sort: {
created_at: -1,
},
},
])
.toArray();
context.response.body = all.filter((value, index, self) => {
return self.findIndex((v) => v.url === value.url) === index;
});
}
我尝试添加索引,但仍需要 5-10 秒才能响应。
-
还请显示集合上的索引和 mongodb 正在使用的查询计划(运行解释)。每个集合中的文档数量肯定会与机器的 RAM 一起提供帮助。
-
我为
explain运行什么命令?机器有 64gb 内存 -
> db.search_history.explain(\'allPlansExecution\') Explainable(grazily.search_history