Recommended way/place to create index on MongoDB c

2019-02-14 00:12发布

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 collection ?

Couple of options I can think of:-

1) 'ensureIndex' on the collection while initializing the application. [But how will I 'ensureindex' at the very first time application initialize ? since there won't be any data in place]

2 'ensureIndex' before every 'find' operation (on web request) ? but isn't this an overhead even if 'ensureIndex' wouldn't create index if it is already created ?

Any other options ?

Thanks in advance.

3条回答
贼婆χ
2楼-- · 2019-02-14 00:39

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.

查看更多
SAY GOODBYE
3楼-- · 2019-02-14 00:43

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.

查看更多
你好瞎i
4楼-- · 2019-02-14 00:50

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.

查看更多
登录 后发表回答