如何在开发模式下优化大量记录的MongoDB查询



我的 mongodb 中有 10000 条记录,当我尝试获取数据并对该数据应用一些过滤器并将响应发送回客户端时,完成查询并将响应发送回客户端需要 14 或 15 秒。如何优化查询?我在我的节点应用程序中使用 mongoosejs 库。这是我的代码。

const mongoose = require('mongoose')
const { Schema } = mongoose
const StaffSchema = new Schema({
   deptName: {type:String},
   numberOfMembers: {Number}
})
const CollegeSchema = new Schema({
  collegeId:{type:Number},
  collegeName:{type:Number},
  numberOfDepartments: {type:Number},
  founder: {type:String},
  website: {type:String},
  university: {type:String},
  telephone: {type:Number}
  numberOfCoursesAvailable:{type:Number},
  staff: [StaffSchema]
  country: {type:String}
})
module.exports = mongoose.model('College', CollegeSchema, 'colleges')

我正在按关键字过滤大学,可以是大学或国家。

let totalColleges = []
if(country) {
totalColleges = College.find({ country })
} 
if(university) {
 totalColleges = College.find({ university })
}

要获取大量数据(如 10,000 条记录(,需要大量时间我们可以选择在生产模式下进行集群。请让我知道如何在开发模式下优化它。

您能做的最好的事情是在用于在查询中更频繁地查询的字段上添加索引

进一步限制记录数(分页(和/或限制文档中要返回的字段(投影(可用于优化性能,但这些取决于您的要求。

另请查看以下链接:

-> https://docs.mongodb.com/manual/core/query-optimization/

-> https://www.yudiz.com/mongodb-query-optimization-techniques/

希望这对:)有所帮助

一般来说,我遵循以下几点。

  • 尽量减少填充的使用。如果您使用填充,则使用选择。示例:Model.find().populate({path:'xyz',select:' name email'})

  • 必要时使用选择。示例:Model.find().select(firstname lastname email)

  • 使用
  • 聚合函数,然后使用其中的$project字段。

    示例:Model.aggregate([{$match:{_id:{$exists:true}}},{$project:{_id:1,name:1,email:1}},])

最新更新