Does createIndex return before the index build is complete in MongoDB 4.2+?

When using createIndex in MongoDB 4.2+(Node.js driver), the docs say that all indexes are created in the foreground with exclusive locks only in the beginning and end of the operation. But will the actual createIndex function resolve before the index build is complete? Or will it resolve once the index has been completely built and is ready for use?

Hi :wave: @Anders_Fjeldstad,

Welcome to the MongoDB Community forums :sparkles:

Based on my understanding, it resolves once the index is completely built unless the background: true option is specified. For further information on this topic, please refer to the createIndex - Node.js Driver Documentation.

I hope it helps. Please let us know if you have any further questions.


Ok so since the background option is deprecated and ignored from 4.2 and onwards, createIndex should now resolve only after the full index build is done, is that correct?

Hi :wave: @Anders_Fjeldstad,

Yes, you can also notice this while building the index using the Nodejs driver if there is any error during the index build it will be returned which would indicate it needed to build the entire thing to report the errors.

However in previous MongoDB versions, it will obtain an exclusive lock on the collection (see Index Build Operations on a Populated Collection — MongoDB Manual for a historical perspective on MongoDB 4.0 as an example), hence the need for the background parameter.

Also, note that in MongoDB 4.4+ indexes are built parallelly across the replica set and only mark it ready when all nodes are complete (by default). You can also modify this behavior with the commitQuorum option

Let me know if you have any further questions.


1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.