惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

The GitHub Blog
The GitHub Blog
V2EX - 技术
V2EX - 技术
T
Threat Research - Cisco Blogs
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Tor Project blog
Project Zero
Project Zero
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
Cybersecurity and Infrastructure Security Agency CISA
T
Tenable Blog
P
Privacy & Cybersecurity Law Blog
AWS News Blog
AWS News Blog
Scott Helme
Scott Helme
C
Cisco Blogs
Application and Cybersecurity Blog
Application and Cybersecurity Blog
O
OpenAI News
P
Privacy International News Feed
Google Online Security Blog
Google Online Security Blog
SecWiki News
SecWiki News
The Last Watchdog
The Last Watchdog
NISL@THU
NISL@THU
Attack and Defense Labs
Attack and Defense Labs
G
GRAHAM CLULEY
Security Latest
Security Latest
Help Net Security
Help Net Security
C
Cyber Attacks, Cyber Crime and Cyber Security
Hugging Face - Blog
Hugging Face - Blog
月光博客
月光博客
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
A
Arctic Wolf
Security Archives - TechRepublic
Security Archives - TechRepublic
S
Security @ Cisco Blogs
腾讯CDC
S
Secure Thoughts
WordPress大学
WordPress大学
P
Proofpoint News Feed
H
Help Net Security
Simon Willison's Weblog
Simon Willison's Weblog
小众软件
小众软件
M
MIT News - Artificial intelligence
博客园 - 叶小钗
IT之家
IT之家
G
Google Developers Blog
博客园 - 聂微东
Google DeepMind News
Google DeepMind News
Microsoft Security Blog
Microsoft Security Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
Google DeepMind News
Google DeepMind News
N
News and Events Feed by Topic
N
News and Events Feed by Topic

Hacker News

Introducing Claude Opus 4.7 Qwen Studio The Future of Everything is Lies, I Guess: Where Do We Go From Here? GitHub - SeanFDZ/macmind: Single-layer transformer in HyperTalk for the classic Macintosh Show HN: Agent-cache – Multi-tier LLM/tool/session caching for Valkey and Redis Moving a large-scale metrics pipeline from StatsD to OpenTelemetry / Prometheus GitHub - Nightmare-Eclipse/RedSun: The Red Sun vulnerability repository GitHub - SethPyle376/hiraeth: Local AWS emulator focused on fast integration testing, with SQS support, SQLite-backed state, and a debug-friendly web UI. GitHub - macOS26/Agent: Any AI, replaces Claude Code, Cursor, OpenClaw. Over 18 LLM providers (Claude, OpenAI, Gemini, Ollama, Zai, HF, Qwen) wired into a native Mac app that writes code, builds Xcode projects, bumps versions, manages git, automates Safari, use AppleScript, JS or Accessibility, extend Agent! w/ MCP Servers, run tasks from your iPhone via Messages. YouTube now lets you turn off Shorts I Made a Terminal Pager Burgers | マクドナルド公式 Commands — HackerNews CLI documentation ChatGPT for Excel PiCore - Raspberry Pi Port of Tiny Core Linux Live Nation illegally monopolized ticketing market, jury finds Google Broke Its Promise to Me. Now ICE Has My Data. Founding Engineer at Adaptional | Y Combinator CRISPR takes important step toward silencing Down syndrome’s extra chromosome GitHub - saffron-health/libretto: The AI toolkit for building reliable browser automations US v. Heppner (S.D.N.Y. 2026) no attorney-client privilege for AI chats [pdf] Unexpected €54k billing spike in 13 hours: Firebase browser key without API restrictions used for Gemini requests Retrofitting JIT Compilers into C Interpreters IPv6 – Google The Accursèd Alphabetical Clock Cybersecurity Looks Like Proof of Work Now Fragments: April 14 Cal.com Goes Closed Source: Why AI Security Is Forcing Our Decision | Cal.com - Scheduling Software for Online Bookings Laravel raised money and now injects ads directly into your agent When moving fast, talking is the first thing to break Too much Discussion of the XOR swap trick – Heather Cafe Introduction to Spherical Harmonics for Graphics Programmers The Grand Line Building a Z-Machine in the worst possible language High-Level Rust: Getting 80% of the Benefits with 20% of the Pain GitHub - duguyue100/midnight-captain: Inspired by Midnight Commander, tailored to my taste. How to build a `git diff` driver · Jamie Tanna | Software Engineer Center for Responsible, Decentralized Intelligence at Berkeley The Local Universe’s Expansion Rate Is Clearer Than Ever, but Still Doesn’t Add Up - A new synthesis of astronomical measurements confirms a persistent mismatch that could point to physics beyond current models The air throughout our homes is infused with microplastics. But there are things you can do to breathe less of them The disturbing white paper Red Hat is trying to erase from the internet – OSnews The Future of Everything is Lies, I Guess: Annoyances ‘Abhorrent’: the inside story of the Polymarket gamblers betting millions on war Productive procrastination — Max van IJsselmuiden maps, territory and LMs 447 Terabytes per Square Centimetre at Zero Retention Energy: Non-Volatile Memory at the Atomic Scale on Fluorographane Show HN: Pardonned.com – A searchable database of US Pardons 20 Years on AWS and Never Not My Job The Seasons are Wrong Artemis II crew splashes down near San Diego after historic moon mission We gave an AI a 3 year retail lease in SF and asked it to make a profit | Andon Labs How a dancer with ALS used brainwaves to perform live On filing the corners off my MacBooks Installing every* Firefox extension OpenClaw’s memory is unreliable, and you don’t know when it will break Steve Blank Nowhere Is Safe Chimpanzees in Uganda locked in vicious 'civil war', say researchers watgo - a WebAssembly Toolkit for Go linux/Documentation/process/coding-assistants.rst at master · torvalds/linux GitHub - callumlocke/json-formatter: Makes JSON easy to read. Founding Product Engineer at Bild AI | Y Combinator A compelling title that is cryptic enough to get you to take action on it GitHub - Keychron/Keychron-Keyboards-Hardware-Design: Industrial design files for Keychron keyboards and mice. 100+ models with CAD assets in STEP, DXF, DWG, and PDF. Source-available, with commercial use allowed for original compatible accessories within the license terms. [ANNOUNCE] WireGuardNT v0.11 and WireGuard for Windows v0.6 Released 1D-Chess Helium Is Hard to Replace Cooperative Vectors Introduction | Evolve Keeping a Postgres queue healthy — PlanetScale Our response to the Axios developer tool compromise Do Americans read print books, e-books or audiobooks more? The Zettelkasten Method in Obsidian: A Practical Setup Guide Artemis II Is Competency Porn and We Are Starving For It WeakC4 Flight Viz — Cockpit View A Mexican surveillance giant you’ve never heard of is now watching the U.S. border Surelock: Deadlock-Free Mutexes for Rust RISC-V 101 – what is it and what does it mean for Canonical? | Ubuntu The Problem That Built an Industry How Much Linear Memory Access Is Enough? | Solidean Investigating Split Locks on x86-64 Simplest hash functions Sybilproof reputation mechanisms (2005) [pdf] What is a property? How Complex is my Code? Static code analysis in Kotlin — tools overview Toffoli gates are all you need PGLite evangelism dcmake: a new CMake debugger UI Clojure on Fennel part one: Persistent Data Structures Fragments: April 2 Python Release Python install manager 26.1 The Life and Death of the Book Review - Liberties Introducing Database Traffic Control — PlanetScale Bitcoin miners are losing $19,000 on every BTC produced as difficulty drops 7.8% God sleeps in the minerals Building slogbox Apple Silicon and Virtual Machines: Beating the 2 VM Limit Who was “Not Even Wrong” first? Pokemon Evolution Vs Darwinian Evolution The APL Programming Language Source Code
How to Optimize MongoDB Query Performance with Indexes
2026-05-07 · via Hacker News

Not all slow MongoDB queries are bad queries.

Sometimes the query is fine, but MongoDB does not have a good index to help with your filtering, sorting, and retrieving of the data

In this tutorial, we'll use payments as an example of our database. The collection starts without a useful index for our query. We'll identify the slow operation, learn about the recommended index, explain why the compound index works, and manage it visually in VisuaLeaf.

Payments collection in VisuaLeaf showing currency status amount and paidAt fields
The payments collection includes fields such as currency, status, amount, and paidAt, which we use in the query example.

The workflow is simple:

slow query -> query profiler -> index recommendation -> compound index -> index manager

You can use the same workflow when your own MongoDB collections start to feel slow.

On this page

  1. The Slow Query Problem
  2. The Payments Query We Want to Optimize
  3. Find the Slow Query in VisuaLeaf
  4. Read the Index Recommendation
  5. Why This Compound Index Works
  6. Check and Manage Indexes
  7. Indexing Mistakes to Avoid
  8. FAQ

The Slow Query Problem

When the size of a database is small, queries executed against it yield fast results.

However, as the database size increases, the same query will take more time. This could be due to the necessity to scan several documents, sort a huge set of returned values, or evaluate non-indexed fields.

This additional processing step causes slow queries.
For instance, consider this query:

db.payments.find({
  status: "paid"
})

If there is no useful index for the "status" field, MongoDB may perform a full scan of the collection.

MongoDB Explain Plan showing COLLSCAN for payments query filtered by status paid
The Explain view shows a collection scan because the status query has no useful index.

Not all collection scans are necessarily harmful. It does not matter for small collections. However, on big collections that your application works with each day, this becomes significant.

In case you analyze a query plan, several steps matter:

Stage Meaning
COLLSCAN MongoDB scanned the collection
IXSCAN MongoDB used an index
FETCH MongoDB fetched documents after using an index
SORT MongoDB performed a sort operation
totalDocsExamined: 50000
Returned: 25

That means MongoDB checked 50,000 documents to return only 25.

The goal is not just to make the query look cleaner. The aim is to reduce the workload of MongoDB.

This technical index functionality is detailed in the official MongoDB Indexes documentation.

The Payments Query We Want to Optimize

Let's try with a more realistic one.

Suppose you have payments stored in your database, and you frequently require paid USD payments above a particular amount, sorted in descending order of payment dates.

The query will be like:

db.payments.find({
  currency: "USD",
  status: "paid",
  amount: { $gte: 100 }
}).sort({
  paidAt: -1
})

This query does four things:

If your payments collection has no useful index for this pattern, so MongoDB has to work harder than necessary.

Field What the query does
currency Keeps only payments in USD
status Keeps only paid payments
amount Keeps payments greater than or equal to 100
paidAt Sorts newest payments first

A single-field index can help with simple filters, but this query uses multiple fields.

That is why a compound index makes more sense here. It can support the filter, sort, and range condition together.

We will let VisuaLeaf recommend the exact index after we inspect the slow query.

MongoDB documents compound indexes in the official Compound Indexes documentation.

Find the Slow Query in VisuaLeaf

Do not create indexes because a field looks important.

Find the slow query first. Then index the query pattern.

Use the same payments query from the previous section in the Visual Query Builder. Add filters for currency, status, and amount, then sort by paidAt in descending order.

In VisuaLeaf, the Explain view shows the execution plan, scanned documents, returned documents, execution time, and index usage.

MongoDB Explain Plan in VisuaLeaf Query Builder showing collection scan and documents examined
The Explain view in VisuaLeaf shows whether a MongoDB query uses an index or performs a collection scan.

If MongoDB scans many documents and returns only a few, the query probably needs a better index.

Use AI Explain for a Quick Summary

The Explain view provides technical details, but sometimes you may want a quick summary in plain language.

In VisuaLeaf, AI Explain can read the query analysis and explain why the query is slow. In this `payments` example, it detects a collection scan and shows that MongoDB examined 298 documents to return only 15.

It also suggests creating a compound index for the fields used in the query.

VisuaLeaf AI Explain showing collection scan for payments query
AI Explain summarizes the collection scan and suggests an index.

This is a helpful first suggestion, but for our full query, we also sort by paidAt, so the final recommendation includes paidAt as part of the compound index.

You can also run the same check manually with explain():

db.payments.find({
  currency: "USD",
  status: "paid",
  amount: { $gte: 100 }
}).sort({
  paidAt: -1
}).explain("executionStats")

When you read the result, check these values:

Metric What you check
totalDocsExamined How many documents MongoDB scanned
nReturned How many documents MongoDB returned
executionTimeMillis How long the query took
winningPlan Which execution plan MongoDB selected

Look for IXSCAN when MongoDB uses an index, and COLLSCAN when MongoDB scans the collection. For one query, the Explain view is enough.

For repeated slow operations across collections, use VisuaLeaf Query Profiling. The profiler helps you see slow operations over time, not just one query you are testing manually.

MongoDB Query Profiling Dashboard in VisuaLeaf showing slow operations
Query Profiling in VisuaLeaf helps you identify repeated slow MongoDB operations across collections.

MongoDB also provides database profiling features for slow operations. You can read more in the official Database Profiler documentation.

Read the Index Recommendation

After you find the slow query, check which index would actually help.

In this example, the payments collection has no useful index for the query. VisuaLeaf detects repeated collection scans and recommends a compound index based on the fields used by the query.

MongoDB index recommendations in VisuaLeaf showing the recommended compound index for the payments collection
VisuaLeaf recommends a compound index after detecting repeated collection scans on the payments collection.

The recommendation for the compound index is:

db.payments.createIndex({
  currency: 1,
  status: 1,
  paidAt: -1,
  amount: 1
})

This is useful because the recommendation does not only say “add an index.”

It shows the exact fields and the order.

That order is the important part.

Why This Compound Index Works

The recommended index corresponds to how the query filters and organizes the data.
Once you have created the recommended index, re-run the same query from the Explain view.

MongoDB Explain Plan in VisuaLeaf showing IXSCAN and compound index usage for payments query
After creating the compound index, VisuaLeaf shows that MongoDB uses the index for the payments query.

Now MongoDB uses the compound index instead of scanning the full collection.

The query initially filters by the currency and status fields, then sorts by paidAt, and applies a range filter to amount.

In other words:

Field Why it is in the index
currency Exact filter
status Exact filter
paidAt Sort by newest payment
amount Range condition

Check and Manage Indexes

Once you’ve indexed something, take a look at what is already there in the collection.
Indexing is simple to do, and it’s easy to neglect.
A collection may accumulate unnecessary indexes, redundant indexes, or even indexes made for queries that no longer run.
Check out your collection in the Index Manager

MongoDB Index Manager in VisuaLeaf showing indexes for a payments collection
The Index Manager shows existing MongoDB indexes, their type, usage, properties, and status.

The Index Manager helps you check the index name, fields, type, size, usage, properties, and status.

This helps you avoid creating the same index twice.

It also helps you review old indexes when your application queries change.

You can combine this workflow with the Visual Query Builder, MongoDB Shell, Aggregation Pipeline Builder, and Charts and Dashboards when you need to test, analyze, and present your MongoDB data.

If you prefer, you can create the index visually from the Index Manager instead of writing the command manually.

Create MongoDB index visually in VisuaLeaf Index Manager with field direction and index options
You can create an index visually from the Index Manager instead of writing the command manually.

Indexing Mistakes to Avoid

Indexes help when they match your workload.

They create problems when you add them without a reason.

  1. Creating indexes for every field

Do not index every field in the collection.

Each index needs storage. Each index also adds work when MongoDB inserts, updates, or deletes documents.

Create indexes for queries your application actually runs.

  1. Ignoring the sort

A query may filter quickly but still sort slowly.

Example:

db.payments.find({
  status: "paid"
}).sort({
  paidAt: -1
})

A useful index is:

db.payments.createIndex({
  status: 1,
  paidAt: -1
})

This supports the filter and the sort.

  1. Putting fields in the wrong order

A compound index is not only about choosing the right fields. The order matters too.

For the payments query, starting with the amount is not as useful as starting with the currency and status, because the amount is a range condition.

Same fields. Different order. Different performance.

  1. Keeping indexes you no longer use

Your application changes.

Your queries change.

Your indexes should change too.

Review unused indexes from time to time and remove the ones that no longer support real queries.

Conclusion

MongoDB query optimization starts with the query pattern.

Do not guess. Find the slow query first. Check whether MongoDB scans too many documents. Then create an index that matches how your query filters, sorts, and ranges over the data.

For simple filters, a single field index may be enough.

For queries like the payments example, a compound index is usually better.

With VisuaLeaf, you can detect slow queries, review index recommendations, and manage MongoDB indexes visually in one place.

Download for Free

FAQ

Why is my MongoDB query slow?

Your query is slow because MongoDB scans too many documents, sorts too much data, or uses the wrong index. Start with explain("executionStats"). Check totalDocsExamined, nReturned, and the winning plan.

What is the best index for a MongoDB query?

The best index matches the fields used by the query. If your query filters by one field, a single field index may work. If your query filters, sorts, and uses a range condition, a compound index is usually better.

What is a compound index in MongoDB?

A compound index is an index with multiple fields. Use it when your query filters or sorts using more than one field.

Example:

db.payments.createIndex({
currency: 1,
status: 1,
paidAt: -1,
amount: 1
})

What is the ESR rule in MongoDB?

ESR means Equality, Sort, Range. Put equality fields first, sort fields second, and range fields last in many compound index designs.

Example:

currency: equality
status: equality
paidAt: sort
amount: range

How do I know if MongoDB uses my index?

Run explain("executionStats").

Look for IXSCAN. That means MongoDB used an index.

Look for COLLSCAN. That means MongoDB scanned the collection.

Can too many indexes slow MongoDB down?

Yes. Too many indexes add storage cost and write overhead. Create indexes for real queries, not for every field.