MongoDB查找 - >匹配 - >小组花太多时间
我已经部署了一个生产应用程序,并且每天都会生成大量数据。但是此查询通常需要大约15秒钟才能完成。这是不好的。我想要很快。如何重写此查询以进行优化以及这里出了什么问题?
const activity_data = await Activity.aggregate([
{
$lookup: {
from: 'tokens',
localField: 'n_id',
foreignField: 'token_id',
as: 'sale_status'
},
},
{
$match: {
activity_type: 'FOR_SALE',
'sale_status.for_sale': true,
}
},
{
$group: {
_id: '$n_id',
createdAt: { $max: '$createdAt' },
},
},
{
$sort: { createdAt: -1 }
},
{
$limit: 15
}
]);
I have a production app deployed and it generates a good amount of data every day. But this query usually takes around 15 seconds to complete. This is not okay. I want it way quickly. How do I rewrite this query for optimization and what went wrong here?
const activity_data = await Activity.aggregate([
{
$lookup: {
from: 'tokens',
localField: 'n_id',
foreignField: 'token_id',
as: 'sale_status'
},
},
{
$match: {
activity_type: 'FOR_SALE',
'sale_status.for_sale': true,
}
},
{
$group: {
_id: '$n_id',
createdAt: { $max: '$createdAt' },
},
},
{
$sort: { createdAt: -1 }
},
{
$limit: 15
}
]);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
简要查看您的查询,您可以进行一些小调整以最大程度地减少中间结果。
您可以看到
activity_type
过滤器已移至早期阶段。for_sale
过滤器还将过滤器移至子围栏中,以最大程度地减少查找结果。如果给出更多的查询上下文,可能会有更多的事情要做。说
$ lookup
如果将for_sale
字段划定到活动
集合是一个选项,则可以跳过。From a brief look at your query, you can do some minor tweaks to minimize the intermediate result.
You can see the
activity_type
filter is moved to earlier stage. Thefor_sale
filter is also moved into a sub-pipeline to minimize lookup results.There are potentially more things to do if more context on your query is given. Say the
$lookup
could have been skipped if denormalizing thefor_sale
field into theActivity
collection is an option.