查询集合对MongoDb的排序速度很慢

时间:2020-02-03 10:03:59

标签: mongodb mongodb-query aggregation-framework

我的mongodb数据库中有两个集合,如下所示:

employee_details 约有330000个文档,其中 department_id 作为部门集合的参考

具有两个字段 _id dept_name

部门 集合

我想通过使用查找方法将Department_id作为外键加入以上两个集合。联接工作正常,但是当我添加排序时,mongo查询执行会花费很长时间。

注意:如果删除排序对象或删除查找方法,则执行速度很快。

我在不同的博客和SO上都提到了几篇文章,但没有一篇给出具体的解决方案。

我的查询如下:

db.getCollection("employee_details").aggregate([
  {
    $lookup: {
      from: "departments",
      localField: "department_id",
      foreignField: "_id",
      as: "Department"
    }
  },
  { $unwind: { path: "$Department", preserveNullAndEmptyArrays: true } },
  { $sort: { employee_fname: -1 } },
  { $limit: 10 }
]);
 

有人可以提供一种使上述查询立即运行的方法吗,因为我的客户端无法妥善处理性能延迟。我希望有某种方法可以解决性能问题,因为nosql旨在处理大型数据库。

有没有可用的索引方法?这样我就可以将其与相同的集合结构一起使用。

谢谢。

1 个答案:

答案 0 :(得分:1)

当前将对每个employee_details进行查找,这将进行330000次,但是如果我们在查找之前先进行排序和限制,则将只有10次。这将大大减少查询时间。

db.getCollection('employee_details').aggregate([
    {$sort      : {employee_fname: -1}},
    {$limit     :10},
    {
        $lookup : {
            from         : "departments",
            localField   : "department_id",
            foreignField : "_id",
            as           : "Department"
        }
    },
    { $unwind   : { path: "$Department", preserveNullAndEmptyArrays: true }},
]) 

尝试此操作后,如果您甚至想减少响应时间,都可以在排序字段上定义index

db.employee_details.createIndex( { employee_fname: -1 } )