Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb indexing optional fields

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?

like image 287
jtmarmon Avatar asked Oct 19 '22 18:10

jtmarmon


1 Answers

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 } )
like image 70
Guillaume Massé Avatar answered Oct 27 '22 19:10

Guillaume Massé