What is the overhead of providing Index ({field: 1}) when the index already exists?

I would always want my collections to be indexed, and I add them and periodically replace them on a regular basis.

Assuming I create a new database connection with every web request, would it be ok to execute several db.collection.ensureIndex ({field: true}) statements every time I connect?

+4
source share
1 answer

As I understand it, MongoDB will simply ask the system collection to see if the index exists before it is created ...

http://www.mongodb.org/display/DOCS/Indexes#Indexes-AdditionalNotesonIndexes

> db.system.indexes.find(); 

You can run getIndexes () to see the collection indices

 > db.things.getIndexes(); 

So you just add one request; he would not rebuild it or do anything else that was not obvious.

However, I do not think this will be a particularly good idea. This will add unnecessary overhead, and it can worse lock up your database as the index is created ... since by default creating the index locks your database (unless you run it in the background):

 > db.things.ensureIndex({x:1}, {background:true}); 

However, note ...

... in the background mode, a gradual approach is used to build the index, which is slower than the default foreground mode: the time to create the index will be longer.

I think it would be much better to do this in code when you add collections , and not every time you connect to the database. Why are you adding and dropping them anyway?

+8
source

Source: https://habr.com/ru/post/1334140/


All Articles