When/how to set indices?

The guide and docs do not seem to contain any info regarding how and when you’d set an index. Afaik setting an index is done via _ensureIndex() but when should you set an index. Let’s say we have a new collection, can we set the index on startup? Does it matter when you set an index? I. e. what if we have existing data but no index has been set yet?

1 Like

You would normally set your indexes in the server’s Meteor.startup(), because (in a perfect world) this only ever runs once - when the node process first starts. Fortunately, the overhead of adding an index which already exists is tiny (check the defined indexes and skip), so it doesn’t matter too much that we’re forever restarting our server processes :wink:!

If you add an index to a collection which doesn’t have that index. MongoDB sets it up for you - the bigger the collection, the longer this takes. The database engine does this in the background, so it shouldn’t affect you - but I haven’t actually tested this in Meteor to see if the fiber is blocked until the indexing completes. In any event, there are ways around that.

And you can, of course, add indexes with the MongoDB shell if you want.

2 Likes

Thanks, as always very helpful :slight_smile: . Pinging @sashko because this info should probably be in the guide (search doesn’t reveal anything in the docs nor the guide)

2 Likes

I think one other tricky thing to note is that if your data doesn’t already adhere to the indices, then mongo won’t apply them.

(Found this out when applying a long list of indices and noting that the fail text is pretty hard to spot unless you’re looking for it in the console.)

2 Likes