I\'m using MongoDB for our web application. Assume there will be a \'find()\' on MongoDB for incoming requests. What is the recommended way/place to add index on a MongoDB c
You could create a initialisation script for the collection to be run from the command line of your server (the Mongo docs discuss how to write Mongo scripts and run them from the CLI). Then have it run whenever mongod starts? The script could just call ensureIndex() on the collection object.
I would put it when you initialize the application. If the collection does not exist when you call ensureIndex, the index (and collection) will be created at that time.
I am assuming that you know a priori what kinds of queries you will be running on the data, and what kind of data you will be putting into the index, of course.
Clearly run the ensureIndex when you start the application. It doesn't matter if you call the ensureIndex on an empty collection (as it will add the data afterwards to the index).
Furthermore it depends on which property your queries are based. If you for example query based on the logged in user, then you should add the index on the user id.