I'd like to always ensure that my collections are indexed, and I'm adding and dropping them on a semi-regular basis.
Assuming that I make a new connection to the DB with every web request, would it be okay to execute a few db.collection.ensureIndex({field:true}) statements every time I connect?
As I understand it MongoDB will simply just query the system Collection to look to see if the index exists before it creates it ...
http://www.mongodb.org/display/DOCS/Indexes#Indexes-AdditionalNotesonIndexes
> db.system.indexes.find();
You can run getIndexes() to see a Collection's indexes
> db.things.getIndexes();
So really, you'd just be adding one query; it would not rebuild it or do anything else non-obvious.
That said, I don't think this would be a particularly good idea. It would add unneeded overhead, and worse might lock your database as the index is created ... since by default creating an index blocks your database (unless you run it in the background) like so:
> db.things.ensureIndex({x:1}, {background:true});
However note ...
... background mode building uses an incremental approach to building the index which is slower than the default foreground mode: time to build the index will be greater.
I think it would be much better to do this in code when you add the collections instead of everytime you connect to the database. Why are you adding and dropping them anyhow?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With