Press enter to see results or esc to cancel.

Initializing MongoDB as a Service on Windows (with Replicas)

The purpose of this post is to document the required steps for setting up MongoDB as a Windows Service including Replicas. Replicas are required for transaction management in MongoDB.

Here is the configuration file for the PRIMARY instance of MongoDB.

# mongod.conf

# data directory
dbpath=C:\Program Files\MongoDB\data\db

# log file
logpath=C:\Program Files\MongoDB\log\mongo.log

logappend=true

#port number 
port=27017

#replica set name
replSet=rs1

Here is the configuration file for the SECONDARY instance of MongoDB.

# mongod1.conf

# data directory
dbpath=C:\Program Files\MongoDB\data\db2

# log file
logpath=C:\Program Files\MongoDB\log2\mongo.log

logappend=true

# port number
port=47017

# replica set name
replSet=rs1

Start both MongoDB instances as a Windows service.

mongod --config C:\Users\Administrator\Documents\mongod.cfg --install
mongod --config C:\Users\Administrator\Documents\mongod1.cfg --serviceName MongoDB1 --serviceDisplayName MongoDB1 --install

Start both instances of MongoDB (as a service)

net start mongodb
net start mongodb1

Verify the status of both services

sc query mongodb
sc query mongodb1

Now connect to the PRIMARY instance using MongoDB shell

mongo --port 27017

Type the below lines to define the config, initialize it and then check status

config = { _id: "rs1", members:[{_id : 0, host : "localhost:27017"},{_id : 2, host : "localhost:47017"}]}
rs.initiate(config)
rs.status()

You can also connect to the SECONDARY instance using the below shell command

mongo --port 47017
Comments

Leave a Comment