MongoDB,Mongoose – 读取10k +文档时查询缓慢

我有一个集合中有10-12k文档的MongoDB数据库,在尝试获取所有文档时遇到了非常慢的查询,如下所示:

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

这个查询获取大约10.5k文件,并且需要1000-1300ms执行。 我尝试删除“在哪里”的条件 – 它只会使速度变慢(更多的文件提取?)。

问题来自Mongoose,MongoDB,JavaScript或Node吗? 我曾经运行过PHP / MySQL数据库,在类似的情况下速度要快10-20倍,比如获取10k +行的数据。 我究竟做错了什么?

编辑

销售模式:

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

来自RoboMongo桌面客户端的查询结果:

 db.getCollection('sales').find({}).explain() executionTimeMillis: 46 nReturned: 10359 

问题来自mongoose。 默认情况下,find()会将文档作为Mongoose文档返回,这会花费很多。 通过在查询中添加lean(),将文档作为普通的JavaScript对象返回,对于10k +返回的文档,查询时间减less了3-5次

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

阅读更多: http : //www.tothenew.com/blog/high-performance-find-query-using-lean-in-mongoose-2/