2

I had to create indices for a collection. I created it but it affected all the requests on the other collections in the other database.

From doc, I read that index creation blocks all read/write locks on all the databases. What is the reason behind such behavior of mongo DB?

  • Locking that collection is the best.
  • Locking that database is acceptable.
  • Locking all the databases is confusing me.
1
  • 2
    not sure why this question is being marked to close.. Commented Mar 13, 2020 at 8:43

1 Answer 1

8

There are two ways to build indexes on MongoDB -

1) Foreground : If you're using MongoDB version <4.2 all indexes are by default build Foreground, Which has better data structures & fast in process but major downside would be while indexes getting build it blocks all operations on database. Which has to be avoided on usual prod servers.

2) Background : So for all versions below 4.2 to overcome con of foreground build process of blocking database activities, there is an option {background :true} to build indexes in background, here while MongoDB is building indexes you can still do reads & writes but cons with this approach is the index structure is least performant & index build time is more.

For MongoDB v >= 4.2, building indexes on background is deprecated, So you can no more specify it & take advantage of background indexes, So MongoDB itself internally builds indexes in background fashion but there would be a lock on the particular collection at start of index build & at end of the build, rest apart mostly you can go ahead with your reads & writes, but somehow there will be 'intent exclusive IX lock' which will intermittently lock the collection & after certain stages there will be lock on writes & then a complete lock, which will finally be released at the end. But why ? So this is to take advantage of fastness & better data structures of foreground + non locking mechanism of background build process.

Ref : .createIndex() & index-creation-process

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for explaining with versions and background option is really useful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.