2 / 2
Apr 2024

I’m encountering performance issues with a MongoDB query used to count contacts belonging to specific contact groups. Initially, this approach worked well with a small dataset, but as the number of contacts in the collection has scaled to over 800k documents, the query’s execution time has become prohibitively slow (approximately 16-25 seconds).

Database Schema:

Schema for Contact:

const Contact = new mongoose.Schema( { name: String, email: { type: String, required: true }, user: { type: mongoose.Schema.Types.ObjectId, ref: "User" }, groups: [{ type: mongoose.Schema.Types.ObjectId, ref: "ContactGroup" }] }, { timestamps: true } );

Schema for ContactGroup:

const ContactGroup = new mongoose.Schema( { title: { type: String, required: true }, description: { type: String, default: "" }, user: { type: mongoose.Schema.Types.ObjectId, ref: "User" }, }, { timestamps: true } );

The query I’m running:

const countdocs = async (query) => { return Contact.countDocuments(query); }; const dt = await countdocs({ $expr: { $in: [mongoose.Types.ObjectId(group._id), "$groups"] } });

I’ve attempted to create an index on the groups field in the Contact collection, but the query’s performance remains suboptimal. Could anyone suggest alternative approaches or optimizations to improve the query’s execution time? Additionally, I’m open to feedback on the current data modeling and indexing strategies.

Any assistance or insights would be greatly appreciated. Thank you!