3

Some questions:

  1. If I ensureIndex on a field that has already been indexed will it re-index or simply say something like yes I've already indexed?
  2. Will mongo start indexes if the collection does not exist yet on some developer's machine?
  3. Do I ever need to ensureIndex again or is calling it once enough?
  4. When is it "safe" to index? It must take some time... During that time is my DB locked?

Thanks!

Parris
  • 17,833
  • 17
  • 90
  • 133

1 Answers1

8
  1. Redundant calls to ensureIndex are no-ops.
  2. If the collection referenced in the ensureIndex call doesn't exist it will be created.
  3. Once is enough.
  4. Unless you specify the background: true option, creating an index blocks other database operations.

MongoDB 3.0 Update

ensureIndex was deprecated in v3.0 and is now an alias for createIndex, so createIndex should be used instead. The behavior remains the same.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • 1
    As to when it is safe: this is upto your load, servers and scenario. Using background building should help in a production envo but it can still crash clusters so be wary. – Sammaye Sep 22 '12 at 22:31