MongoDB allows you to create an index on fields that may not exist in all documents, in a given collection. These are called sparse indexes and in this recipe, we will look at how to create them.
For this recipe, load the sample dataset and create an index on the city
field, as described in the Creating an index recipe.
- Check the total number of documents in our collection and number of documents without the
language
field:
db.mockdata.count()
The preceding command should return 100000
.
db.mockdata.find({language: {$eq:null}}).count()
The preceding command should return 12704
.
- Create a sparse index on the document:
db.mockdata.createIndex({language:1}, {sparse: true})
You should see output similar to this:
{ "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
- Check our index got created with the
sparse
parameter:
db.mockdata.getIndexes()
The preceding command should give you output similar...