简体   繁体   English

MongoDB,Mongoose - 获取10k +文档时查询速度慢

[英]MongoDB, Mongoose - Slow query when fetching 10k+ documents

I have a MongoDB database with 10-12k documents in a collection and I'm experiencing really slow queries when attempting to fetch all documents, like this: 我有一个包含10-12k文档的MongoDB数据库,在尝试获取所有文档时遇到的查询速度非常慢,如下所示:

Sales.find()
    .where('author').equals(author)
    .where('date').gt(startDate.unix()).lt(endDate.unix())
    .exec(function(err, results) {
        callback();
    });

This query fetches around 10.5k documents and it takes 1000-1300ms to execute. 此查询提取大约10.5k文档,执行时需要1000-1300ms。 I tried removing the "where" conditions - it only makes it slower (more documents fetched?). 我尝试删除“where”条件 - 它只会使它变慢(获取更多文档?)。

Does the problem come from Mongoose, MongoDB, JavaScript or Node? 问题来自Mongoose,MongoDB,JavaScript还是Node? I used to run PHP/MySQL database and it was 10-20 times faster in similar conditions, like fetching 10k+ rows of data. 我以前运行PHP / MySQL数据库,在类似条件下速度提高10-20倍,比如获取10k +行数据。 What am I doing wrong? 我究竟做错了什么?

EDIT 编辑

Sales schema: 销售架构:

var salesSchema = new Schema({
    author: String,
    kind: String,
    productID: String,
    description: String,
    date: String,
    amount: String,
    transactionID: {
        type: String,
        unique : true
    }
});

Query result from the RoboMongo desktop client: 来自RoboMongo桌面客户端的查询结果:

db.getCollection('sales').find({}).explain()

executionTimeMillis: 46
nReturned: 10359

The problem came from Mongoose. 问题来自Mongoose。 By default, find() will return documents as Mongoose Documents, which costs a lot. 默认情况下,find()会将文档作为Mongoose Documents返回,这会花费很多。 By adding lean() to the query, documents are returned as plain JavaScript objects and for this case of 10k+ returned documents, the query time got reduced 3-5 times . 通过向查询添加lean(),文档作为纯JavaScript对象返回,对于10k +返回文档的情况,查询时间减少了3-5倍

Sales.find()
    .where('author').equals(author)
    .where('date').gt(startDate.unix()).lt(endDate.unix())
    .lean()
    .exec(function(err, results) {
        callback();
    });

Read more here: http://www.tothenew.com/blog/high-performance-find-query-using-lean-in-mongoose-2/ 在这里阅读更多内容: http//www.tothenew.com/blog/high-performance-find-query-using-lean-in-mongoose-2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM