Can I modify existing index in MongoDB without dropping it?

13,396

There is no way to alter an index as you describe, and if there was I think the outcome in terms of performance would be similar - how would the database use the half created/altered index while this operation was going on for example?

Instead I would recommend using the background option to build the index on a single node, if that is your configuration - it will take longer but will not interfere with your normal operation as much. Once it is finished you can drop the old index at your leisure.

However, if you have a replica set (recommended) you should be aware that index creation is always (currently) done in the foreground on the secondary. If you want to avoid load on your secondaries, then you should follow the steps outlined here to take a member out one at a time and build the index required before rejoining the set:

http://docs.mongodb.org/manual/administration/indexes/#index-building-replica-sets

Update

Background index builds on secondaries will be possible starting with the 2.6 release (see release notes for details). This is not going to be backported to prior versions, so the above note will be true for versions prior to 2.6.

Finally, As a general note, indexes built in the background will generally be larger and a less efficient than those built in the foreground, so the methodology above will still have its uses.

Share:
13,396

Related videos on Youtube

expert
Author by

expert

My interests: scala kotlin java deep-learning machine-learning reactive-programming scala-cats project-reactor scalability reverse-engineering peer-to-peer. Back in 2005 I created Morpheus, the most popular file sharing application in North America. I also designed and built Dell Digital Delivery (similar to Steam for non-games) which is installed on every Dell PC world-wide and worked on improving architecture of Fivetran. Currently I'm building super-fast hybrid (batching/realtime) data integration pipeline at bitparticles.

Updated on June 04, 2022

Comments

  • expert
    expert almost 2 years

    Can I modify existing index in MongoDB without dropping it ? I don't see anything about it in documentation.

    I have an non-unique index on String field. Collection is ~6M documents. It's replica set.

    I know I can delete index and add new one. But it's problematic due to two reasons:

    1) at time while index doesn't exist some queries will be very very slow. 2) adding new index (in my project) creates very high load on DB which visibly slows down my web-site.

  • ProgrammingLlama
    ProgrammingLlama over 7 years
    Your first paragraph misses the case where you might want to set an index to sparse without the performance loss for quries while this is happening.