From de92ce5c49c178cebbc046b4c09cf0f22dc5940e Mon Sep 17 00:00:00 2001 From: Benjamin Simonsson <31991798+BenniPlejd@users.noreply.github.com> Date: Fri, 28 Dec 2018 15:45:36 +0100 Subject: [PATCH] Fix for count being very slow on large Parse Classes' collections (#5264) * * Added fix for MongoCollection's count function, so that it uses the much more effecient estimatedDocumentCount if no queries were specified * * Added missing options when running estimatedDocumentCount for Mongo Collections * * Fixed issue with checking for zero query for Mongo Collections count --- src/Adapters/Storage/Mongo/MongoCollection.js | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/Adapters/Storage/Mongo/MongoCollection.js b/src/Adapters/Storage/Mongo/MongoCollection.js index bcc774af..50e7a411 100644 --- a/src/Adapters/Storage/Mongo/MongoCollection.js +++ b/src/Adapters/Storage/Mongo/MongoCollection.js @@ -80,6 +80,16 @@ export default class MongoCollection { } count(query, { skip, limit, sort, maxTimeMS, readPreference } = {}) { + // If query is empty, then use estimatedDocumentCount instead. + // This is due to countDocuments performing a scan, + // which greatly increases execution time when being run on large collections. + // See https://github.com/Automattic/mongoose/issues/6713 for more info regarding this problem. + if (typeof query !== 'object' || !Object.keys(query).length) { + return this._mongoCollection.estimatedDocumentCount({ + maxTimeMS, + }); + } + const countOperation = this._mongoCollection.countDocuments(query, { skip, limit,