Question

I've seen the instructions for creating indexes on replica sets in MongoDB here. It looks fairly involved and requires the mongo shell. Is there an easier way and/or can this be done using C# MongoDB driver?

Was it helpful?

Solution

As you can see in the docs, there are 4 possible stages for both primaries and secondaries:

  • Build the index in the background on the primary.
  • Build the Index
  • Stop One Secondary
  • Restart the Program mongod

The first two you can do using the driver, because mongod is up. Use EnsureIndex with the right parameters.

For the next two you can't use the driver but you can still do programmatically as you would in a command prompt:

var stop = Process.Start("mongod", "--shutdown");
var standalone =  Process.Start("mongod", "--port 47017");
var replicated = Process.Start("mongod", "--port 27017 --replSet rs0");

OTHER TIPS

I would suggest this process to build a index on a replica set. Call it a "Rolling index build". For example assume you have 2+1 replica set

  1. Take down the secondary from the replica set and add the index. Once the index is built you can bring it back up and let it catch up to the primary
  2. Take down the primary and repeat the same process as 1.
  3. You can decide if the old primary needs to become primary again or you are fine with the other server being primary.

Don't build the index on the background in the primary since it will be built on the foreground in the secondary (and this could take down the secondary). This behaviour is being changed in 2.6.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top