[英]Why is my MongoDB aggregation query so slow
I have several IDs (usually 2 or 3) of users whom I need to fetch from the database.我有几个需要从数据库中获取的用户 ID(通常是 2 或 3 个)。 Thing is, I also need to know the distance from a certain point.
问题是,我还需要知道到某个点的距离。 Problem is, my collection has 1,000,000 documents (users) in it, and it takes upwards of 30 seconds to fetch the users.
问题是,我的集合中有 1,000,000 个文档(用户),获取用户需要 30 秒以上。
Why is this happening?为什么会这样? When I just use the
$in
operator for the _id
it works fine and returns everything in under 200ms, and when I just use the $geoNear
operator it also works fine, but when I use the 2 together everything slows down insanely.当我只对
_id
使用$in
运算符时,它可以正常工作并在 200 毫秒内返回所有内容,而当我只使用$geoNear
运算符时,它也可以正常工作,但是当我将 2 一起使用时,一切都会变慢。 What do I do?我该怎么办? Again, all I need is a few users with the IDs from the
userIds
array and their distance from a certain point ( user.location
).同样,我所需要的只是一些具有来自
userIds
数组的 ID 以及他们与某个点 ( user.location
) 的距离的用户。
EDIT: Also wanted to mention that when i use $nin
instead of $in
the query also performs pefrectly.编辑:还想提一下,当我在查询中使用
$nin
而不是$in
,它也能很好地执行。 Only $in
is causing the problem when combined with $geoNear
与
$geoNear
结合使用时,只有$in
会导致问题
const user = await User.findById('logged in users id');
const userIds = ['id1', 'id2', 'id3'];
[
{
$geoNear: {
near: user.location,
distanceField: 'distance',
query: {
_id: { $in: userIds }
}
}
}
]
I found a work-around: i just query by the ID field, and later I use a library to determine the distance of the returned docs from the central point.我找到了一个解决方法:我只是通过 ID 字段进行查询,然后我使用一个库来确定返回的文档到中心点的距离。
Indexing your data could be a solution to your problem.索引您的数据可能是您的问题的解决方案。 without indexing mongodb has to scan through all documents.
没有索引 mongodb 必须扫描所有文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.