Creating a partial index
Partial indexes were introduced recently, in MongoDB Version 3.2. A partial index is slightly similar to sparse index but with the added advantage of being able to use expressions ($eq
, $gt
, and so on) and operators ($and
).
Getting ready
For this recipe, load the sample dataset and create an index on the city
field, as described in the Creating an index recipe.
How to do it...
- 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( {first_name:1}, {partialFilterExpression: { language: {$exists: true}}} )
This should give you output similar to this:
{ "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
- Confirm that the index was created:
db.mockdata...