MongoDB请求变得非常慢,即使使用索引也是如此
我正在构建一个mongodb应用程序,我只是想知道,如果文档数量超过1.000.000,为什么我的请求(即使有索引)会变得非常慢 我的模式如下所示:MongoDB请求变得非常慢,即使使用索引也是如此,mongodb,mongoose,mongodb-indexes,Mongodb,Mongoose,Mongodb Indexes,我正在构建一个mongodb应用程序,我只是想知道,如果文档数量超过1.000.000,为什么我的请求(即使有索引)会变得非常慢 我的模式如下所示: const reportSchema = new mongo.Schema({ organisation: { type: mongo.Schema.Types.ObjectId, ref: 'Organisation', required: true }, reference: { type: mo
const reportSchema = new mongo.Schema({
organisation: {
type: mongo.Schema.Types.ObjectId,
ref: 'Organisation',
required: true
},
reference: {
type: mongo.Schema.Types.ObjectId,
required: true
},
belongsTo: {
type: String,
enum: ['endpoint'],
required: true
},
objects: [{
property: {
type: String,
required: true
},
value: {
type: String,
required: true
}
}]
}, {
timestamps: true
});
reportSchema.index({
createdAt: -1,
organisation: 1,
reference: 1
});
我的索引如下所示:
const reportSchema = new mongo.Schema({
organisation: {
type: mongo.Schema.Types.ObjectId,
ref: 'Organisation',
required: true
},
reference: {
type: mongo.Schema.Types.ObjectId,
required: true
},
belongsTo: {
type: String,
enum: ['endpoint'],
required: true
},
objects: [{
property: {
type: String,
required: true
},
value: {
type: String,
required: true
}
}]
}, {
timestamps: true
});
reportSchema.index({
createdAt: -1,
organisation: 1,
reference: 1
});
我的问题是:
this.model.find({
organisation: organisationId,
reference: referenceId
})
.select('_id reference objects createdAt')
.sort('-createdAt')
.then(reports => resolve(reports))
.catch(err => {
console.error(err);
reject();
});
有人能告诉我为什么吗?
该指数是否为失败点?
我的查询错了吗?我建议您查看一下索引的大小。如果您使用的索引不能放入RAM,那么使用该索引将无法提高性能。查看文档的这一部分-用于检查运行此查询时发生的情况,您可以在mongo Shell中执行示例查询。我很确定索引不会用于该查询,因为
组织/参考(在您的查询中)不是一个索引。正如@Astro所建议的,使用.explain()
查看索引是否正在实际使用,但作为快速检查,请尝试创建一个索引{organization:1,reference:1}
和另一个索引{createdAt:-1}
(删除现有索引后)。