Reputation: 6179
I have some fields in my mongodb collection that are optional parts of a search. How can I index this query consistently (i.e. every query, regardless of parameters will use an index) if I don't know what fields the user might be querying?
Upvotes: 8
Views: 5253
Reputation: 8064
You can use a Sparse Index
Sparse indexes only contain entries for documents that have the indexed field, even if the index field contains a null value. The index skips over any document that is missing the indexed field. The index is “sparse” because it does not include all documents of a collection. By contrast, non-sparse indexes contain all documents in a collection, storing null values for those documents that do not contain the indexed field.
db.addresses.createIndex( { "xmpp_id": 1 }, { sparse: true } )
Upvotes: 5