MongoDB 聚合以及使用关联集合字段进行查找和排序会减慢查询速度

标签 mongodb sorting limit lookup

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

employee_details with approximately 330000 documents which has department_id as a reference from departments collection

departments collections with 2 fields _id and dept_name

我已将索引添加到集合中,如下所示

db.departments.createIndex( { dept_name: 1 } )
db.employee_details.createIndex( { department_id: 1 } )
db.employee_details.createIndex( { employee_fname: 1 } )

我想通过连接两个集合来获取要在数据表上列出的数据。但当我尝试这样做时,我遇到了两个问题。

首先,当我在查找后添加排序时,查询运行需要很长时间,我在查找后添加了排序,因为我需要使用集合部门的 dept_name 进行排序。查询如下

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

其次,当我在查找上方添加排序时,查询变得很快,但如果我使用 dept_name 或 Department_id 排序,结果会给出错误的排序(排序对于 employee_details 集合的字段效果很好)。查询如下

db.getCollection("employee_details").aggregate([
  { $unwind: { path: "$Department", preserveNullAndEmptyArrays: true } },
  { $sort: { "Department.dept_name": 1 } },
  //{ $sort: { "department_id": 1 } }, // tried this also
  { $limit: 30 },
  {
    $lookup: {
      from: "departments",
      localField: "department_id",
      foreignField: "_id",
      as: "Department"
    }
  }
]);

有人可以提供一个优化的解决方案来从所有相关集合中获取数据并进行排序吗? 预先感谢您。

最佳答案

试试这个:

db.departments.aggregate([
  {
    $sort: {
      "dept_name": 1
    }
  },
  {
    $lookup: {
      from: "employee_details",
      localField: "_id",
      foreignField: "department_id",
      as: "Employee"
    }
  },
  {
    $unwind: "$Employee"
  },
  {
    $addFields: {
      tmp: {
        $mergeObjects: [
          {
            Department: "$$ROOT"
          },
          "$Employee"
        ]
      }
    }
  },
  {
    $project: {
      "tmp.Department.Employee": 0
    }
  },
  {
    $addFields: {
      "tmp.Department": [
        "$tmp.Department"
      ]
    }
  },
  {
    $replaceRoot: {
      newRoot: "$tmp"
    }
  },
  {
    $limit: 30
  }
])

MongoPlayground

关于MongoDB 聚合以及使用关联集合字段进行查找和排序会减慢查询速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60057388/

相关文章:

通过 XML 限制 Magento 产品集合

php - SQL LIMIT 返回 'zero' - 0 - 行(在 PHP 中)

php - 查询时对相关模型的 Yii 限制

javascript - Mongoose 分页

algorithm - 插入、选择、冒泡排序分析与反演 Robert Sedgewick

python - 在 Python 中从 .csv 文件排序

jquery - 如何对 div 内的表格进行排序

mongodb - 如何启用 mongodb cli pretty-print ? - db.col.find().pretty() 不工作

Java 向 MongoDB 中的数组插入值

javascript - MongoDB 重复键错误