How can I run MongoDB as a Windows service?

After trying for several hours, I finally did it.

Make sure:

  1. you added the <MONGODB_PATH>\bin directory to the system variable PATH
  2. run command prompt as administrator

Steps:

step 1: execute this command:

D:\mongodb\bin>mongod --remove

Step 2: execute this command after opening command prompt as administrator:

D:\mongodb\bin>mongod --dbpath=D:\mongodb --logpath=D:\mongodb\log.txt --install

NOTE: you can also append --serviceName MongoDB after the command above.

That’s All!


After that right there in the command prompt execute:

services.msc

// OR

net start MongoDB

And look for MongoDB service and click start.


NOTE: Make sure to run command prompt as administrator.

If you don’t do this, your log file (D:\mongodb\log.txt in the above example) will contain lines like these:

2016-11-11T15:24:54.618-0800 I CONTROL  [main] Trying to install Windows service 'MongoDB'
2016-11-11T15:24:54.618-0800 I CONTROL  [main] Error connecting to the Service Control Manager: Access is denied. (5)

and if you try to start the service from a non-admin console, (i.e. net start MongoDB or Start-Service MongoDB in PowerShell), you’ll get a response like this:

System error 5 has occurred.
Access is denied.

or this:

Start-Service : Service 'MongoDB (MongoDB)' cannot be started due to the following error: Cannot open MongoDB service
on computer '.'.
At line:1 char:1
+ Start-Service MongoDB
+ ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (System.ServiceProcess.ServiceController:ServiceController) [Start-Service],
   ServiceCommandException
    + FullyQualifiedErrorId : CouldNotStartService,Microsoft.PowerShell.Commands.StartServiceComman

Leave a Comment