Search code examples
c#.netmongodbmongodb-.net-driver

Can creating indexes on MongoDB collections in a replica set be done programmatically?


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?


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");