Menu

Your MongoDB Query Is Slow and You Are Guessing Why: Read explain() Instead
📰

Your MongoDB Query Is Slow and You Are Guessing Why: Read explain() Instead

DEV Community: mongodb·Anas Sheikh·2 days ago
#Yzi3mYHz
#devtomongodb#devto#dev#index#query
Reading 0:00
15s threshold

The endpoint was fast in development. In production it takes two seconds, and it gets slower every week.

So you do what most of us do. You add .lean() . You add an index on a field that sounds important. You wonder if the server is too small. Maybe the slowdown goes away, maybe it does not, and you never learn why.

MongoDB will tell you exactly why, if you ask. The tool is called explain() , and most developers never open it.

The Query

An orders list, the kind every app has:

const orders = await Order . find ({ userId , status : ' paid ' }) . sort ({ createdAt : - 1 }) . limit ( 20 );

Enter fullscreen mode

Exit fullscreen mode

Twenty results, newest first. Looks harmless. Now ask the database what it did:

const plan = await Order . find ({ userId , status : ' paid ' }) . sort ({ createdAt : - 1 }) . limit ( 20 ) . explain ( ' executionStats ' );

console . log ( JSON . stringify ( plan , null , 2 ));

Enter fullscreen mode

Exit fullscreen mode

The output is long.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.