Schema-free design is one of the fundamental features of Mongo. This allows documents in a collection to have disparate fields, with some fields present in some documents and absent in the others. In other words, these fields might be sparse; this might have already given you a clue to what sparse indexes are. In this recipe, we will create some random test data and see how sparse indexes behave against a normal index. We will see the advantage of using a sparse index and one major pitfall in its usage.
For this recipe, we need to create a collection called sparseTest
. We will require a server to be up and running. Refer to the Single node installation of MongoDB recipe in Chapter 1, Installing and Starting the MongoDB Server, to learn how to start the server. Also, start the shell with the SparseIndexData.js
script loaded. This script will be available on the book's website for download. To know how to start the shell with a script reloaded...