CrazyCoder
CrazyCoder

Reputation: 2605

Does MongoDB loads all the index into memory?

Does MongoDB load all the indexes from multiple databases and collections in memory after it starts or whenever it will load indexes only when it encountered a query? I am trying to understand does MongoDB supports the eager or lazy loading of indexes.

Upvotes: 2

Views: 557

Answers (1)

Joe
Joe

Reputation: 28366

It lazily loads indexes. It may even load only part of an index if it doesn't need it in its entirety for the current query.

To demonstrate this:

  1. create a collection with a few thousand documents containing a random integer like {i: <int>}
  2. create an index on {i:1}
  3. check the sizes of the indexes on the collection by running:
db.testcollection.stats().indexSizes
  1. stop the mongod
  2. restart the mongod
  3. check the amount of data in the cache with
db.serverStatus().wiredTiger.cache["bytes currently in the cache"]

At this point you should be able to note that the total amount of data in the cache is less than the size of the indexes on the test collection

  1. run a count command with a query that will be covered by the first part of the index, such as
db.testcollection.count({i:{$lt:50}})
  1. re-run the serverStatus command and note the difference in size
  2. repeat steps 7 and 8, note that the size does not change since the index is already loaded into memory.

If you explain the count command, it should show it using a COUNT_SCAN stage, which means that it is completely service by the index and does not need to load any documents.

Upvotes: 4

Related Questions