190

I need to be able to start/stop MongoDB on the cli. It is quite simple to start:

./mongod

But to stop mongo DB, I need to run open mongo shell first and then type two commands:

$ ./mongo

use admin

db.shutdownServer()

So I don't know how to stop mongo DB in one line. Any help?

Community
  • 1
  • 1
XiaoYao
  • 3,177
  • 4
  • 22
  • 19

20 Answers20

283

Starting and Stopping MongoDB is covered in the MongoDB manual. It explains the various options of stopping MongoDB through the shell, cli, drivers etc. It also details the risks of incorrectly stopping MongoDB (such as data corruption) and talks about the different kill signals.

Additionally, if you have installed MongoDB using a package manager for Ubuntu or Debian then you can stop mongodb (currently mongod in ubuntu) as follows:

  • Upstart: sudo service mongod stop

  • Sysvinit: sudo /etc/init.d/mongod stop

Or on Mac OS X

Or on Red Hat based systems:

  • service mongod stop

Or on Windows if you have installed as a service named MongoDB:

  • net stop MongoDB

And if not installed as a service (as of Windows 7+) you can run:

  • taskkill /f /im mongod.exe

To learn more about the problems of an unclean shutdown, how to best avoid such a scenario and what to do in the event of an unclean shutdown, please see: Recover Data after an Unexpected Shutdown.

Edi
  • 1,900
  • 18
  • 27
Mark Hillick
  • 6,853
  • 1
  • 19
  • 23
  • 6
    I believe the order for service is `sudo service mongodb [start|stop|restart|status]`. `sudo service stop mongodb` results in: _stop: unrecognized service_ – Jakob Jingleheimer Jul 12 '13 at 16:21
  • 2
    @Jacob - We just tried this on ubuntu, you're right, I've edited the answer. – Andrew M Oct 15 '13 at 12:35
  • 6
    For Mac, you can also just do 'killall mongod'. That way, you don't need to know the PID. – Jon M Mar 20 '16 at 14:00
  • One additional warning might help: If you started `mongod` in the foreground, do *NOT* use CTRL-C to shut it down, since this may lead to lost data. – DrMickeyLauer Mar 27 '16 at 10:20
  • 2
    Or on Mac: 'ps -ax | grep mongod', then kill the process number – Bryan Grace Nov 04 '16 at 05:34
  • @Mark When I use the 'net stop MongoDB' on windows it is showing "System Error 1067 has occured" – charan tej Mar 01 '17 at 05:50
  • C:\Program Files\MongoDB\Server\3.2\bin>net start MongoDB The MongoDB service was started successfully. – Vishe Oct 15 '17 at 06:32
  • 1
    In the new Ubuntu 18.04, I am able to stop it using > sudo service mongod stop ... not "mongodb" – naseefo Aug 05 '18 at 21:59
  • Note that on my system the service is named mongod. not mongodb. rhel. – vikingsteve Nov 07 '18 at 09:21
  • For Mac OSX, the given link is not to-the-point. Please refer the below link for clear straight forward instructions: https://docs.mongodb.com/manual/tutorial/manage-mongodb-processes/#stop-mongod-processes – LearnerAllTheWay Oct 23 '19 at 02:20
118

If you literally want a one line equivalent to the commands in your original question, you could alias:

mongo --eval "db.getSiblingDB('admin').shutdownServer()"

Mark's answer on starting and stopping MongoDB via services is the more typical (and recommended) administrative approach.

Stennie
  • 63,885
  • 14
  • 149
  • 175
  • 3
    Great answer. When setting up multiple instances on development machine (trying the replication set before deployment) it helps to have a .bat `start C:\mongodb\bin\mongod.exe --config C:\net2\primary1-pc\mongod.cfg start C:\mongodb\bin\mongod.exe --config C:\net2\secondary1-pc\mongod.cfg ...` and then have shutdown.bat `C:\mongodb\bin\mongo.exe --eval "db.getSiblingDB('admin').shutdownServer()" --port 27017 C:\mongodb\bin\mongo.exe --eval "db.getSiblingDB('admin').shutdownServer()" --port 27018 C:\mongodb\bin\mongo.exe --eval "db.getSiblingDB('admin').shutdownServer()" --port 27019 ...` – Developer Marius Žilėnas Feb 01 '16 at 08:11
  • 3
    On Windows where it's installed as a service, I found that `net stop MongoDB` wasn't reliable, so I used something similar: `mongo admin --eval "db.shutdownServer()"` . Cheers! – NateJ Aug 09 '16 at 21:25
  • 1
    @Stennie When I use the 'net stop MongoDB' on windows it is showing "System Error 1067 has occured" – charan tej Mar 01 '17 at 05:52
57

mongod --dbpath /path/to/your/db --shutdown

More info at official: http://docs.mongodb.org/manual/tutorial/manage-mongodb-processes/

francoisrv
  • 2,457
  • 1
  • 19
  • 13
  • I love using this way, it works without dbpath too, makes sense if you only have one instance running. – radtek May 27 '14 at 03:47
  • 2
    it seems it is not working for newer versions, from 2.4.xx to latest. – alexserver Jun 07 '14 at 06:20
  • This is the only answer that I've seen that actually worked. – David Betz Feb 01 '16 at 04:32
  • 9
    macOS 10.12, `mongod v3.4.10`: `Error parsing command line: unrecognised option '--shutdown'`:-( – t0r0X Nov 21 '17 at 18:35
  • Is there a defined behavior for this if it is run on a primary of a replica set? It seems to behave like `db.shutdownServer({force:1,timeoutSecs:0})` which would inhibit the flushing of remaining data to the secondaries. You might not always want that. – Daniel F Sep 10 '18 at 22:52
39

If the server is running as the foreground process in a terminal, this can be done by pressing

Ctrl-C

Another way to cleanly shut down a running server is to use the shutdown command,

> use admin
> db.shutdownServer();

Otherwise, a command like kill can be used to send the signal. If mongod has 10014 as its PID, the command would be

kill -2 10014
Nanhe Kumar
  • 15,498
  • 5
  • 79
  • 71
  • 3
    Using kill isn't a good idea, this might lead to a broken DB, which needs a repair for restart. "Never use kill -9 (i.e. SIGKILL) to terminate a mongod instance." Docs: http://docs.mongodb.org/manual/tutorial/manage-mongodb-processes/#use-kill – Jens A. Koch Dec 15 '14 at 20:18
  • 8
    @JensA.Koch Ya, Nanhe wasn't telling anyone to use a -9 signal, so.. saying "using kill isn't a good idea" simply isn't accurate. Only instant termination is unsafe - a normal kill is perfectly safe and the documentation you linked to advocates it. – B T Jul 23 '16 at 08:10
24

I followed the official MongoDB documentation for stopping with signals. One of the following commands can be used (PID represents the Process ID of the mongod process):

kill PID

which sends signal 15 (SIGTERM), or

kill -2 PID

which sends signal 2 (SIGINT).

Warning from MongoDB documentation:
Never use kill -9 (i.e. SIGKILL) to terminate a mongod instance.

If you have more than one instance running or you don't care about the PID, you could use pkill to send the signal to all running mongod processes:

pkill mongod

or

pkill -2 mongod

or, much more safer, only to the processes belonging to you:

pkill -U $USER mongod

or

pkill -2 -U $USER mongod

NOTE: If the DB is running as another user, but you have administrative rights, you have invoke the above commands with sudo, in order to run them. E.g.:

sudo pkill mongod
sudo pkill -2 mongod

PS

Note: I resorted to using signals because mongod --shutdown, although mentioned in the current MongoDB documentation, did not work on my machine (macOS, mongodb v3.4.10, installed with homebrew):

Error parsing command line: unrecognised option '--shutdown'

Update 2022-05-10

meanwhile option --shutdown is marked in the documentation as "Supported on Linux only".

PPS

(macOS specific) Before anyone wonders: no, I could not stop it with command

brew services stop mongodb

because I did not start it with

brew services start mongodb

I had started mongod with a custom command line :-)

t0r0X
  • 4,212
  • 1
  • 38
  • 34
  • 1
    Great answer, which confirmed that MongoDB can be gracefully terminated using SIGTERM signal. It is important if running MongoDB in a Docker - https://docs.docker.com/compose/compose-file/#stop_grace_period . Additional note that CMD ["mongod", "option", "option" ] needs to be used to make sure that MongoDB gets PID 1, then signal sent by Docker will reach your DB. – laimison Apr 26 '19 at 17:38
11

Use mongod --shutdown

According to the official doc : manage-mongodb-processes/

:D

Shawn Wang
  • 2,314
  • 1
  • 16
  • 19
8

create a file called mongostop.bat

save the following code in it

 mongo admin --eval "db.shutdownServer()"

run the file mongostop.bat and you successfully have mongo stopped

Adeojo Emmanuel IMM
  • 2,104
  • 1
  • 19
  • 28
8

My special case is:

previously start mongod by:

sudo -u mongod mongod -f /etc/mongod.conf

now, want to stop mongod.

and refer official doc Stop mongod Processes, has tried:

(1) shutdownServer but failed:

> use admin
switched to db admin
> db.shutdownServer()
2019-03-06T14:13:15.334+0800 E QUERY    [thread1] Error: shutdownServer failed: {
        "ok" : 0,
        "errmsg" : "shutdown must run from localhost when running db without auth",
        "code" : 13
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DB.prototype.shutdownServer@src/mongo/shell/db.js:302:1
@(shell):1:1

(2) --shutdown still failed:

# mongod --shutdown
There doesn't seem to be a server running with dbpath: /data/db

(3) previous start command adding --shutdown:

sudo -u mongod mongod -f /etc/mongod.conf --shutdown
killing process with pid: 30213
failed to kill process: errno:1 Operation not permitted

(4) use service to stop:

service mongod stop

and

service mongod status

show expected Active: inactive (dead) but mongod actually still running, for can see process from ps:

# ps -edaf | grep mongo | grep -v grep
root     30213     1  0 Feb04 ?        03:33:22 mongod --port PORT --dbpath=/var/lib/mongo

and finally, really stop mongod by:

# sudo mongod -f /etc/mongod.conf --shutdown
killing process with pid: 30213

until now, root cause: still unknown ...

hope above solution is useful for your.

crifan
  • 12,947
  • 1
  • 71
  • 56
6

Building on the answer from stennie:

mongo --eval "db.getSiblingDB('admin').shutdownServer();quit()"

I found that mongo was trying to reconnect to the db after the server shut down, which would cause a delay and error messages. Adding quit() after shutdown speeds it up and reduces the messages, but there is still one.

I also want to add context - I'm starting and stopping mongod as part of test cases for other code, so registering as a service does not fit the use case. I am hoping to end up with something that runs on all platforms (this tested in windows right now). I'm using mongod 3.6.9

David Fridley
  • 165
  • 1
  • 10
  • I really liked this version. I didnt know the service/ execulable or pid.. or none of them returned expected response. this helped me. – Anand Vaidya Aug 14 '20 at 04:35
5

One liners to start or stop mongodb service using command line;

  1. To start the service use: NET START MONGODB
  2. To stop the service use: NET STOP MONGODB

I use this myself, it does work.

Hugo Dozois
  • 8,147
  • 12
  • 54
  • 58
Pirira
  • 51
  • 1
  • 1
  • I get this on using those commands on windows: c:\mongodb\bin>NET START MONGODB The service name is invalid. More help is available by typing NET HELPMSG 2185. c:\mongodb\bin>NET STOP MONGODB The service name is invalid. More help is available by typing NET HELPMSG 2185. –  Jun 15 '13 at 04:24
  • On windows you first have to install mongodb as a service using the --install option. The commands you can use a command similar to the following to install it as a service. mongod --install --directoryperdb --dbpath C:\mongodb-win32-x86_64-2.4.6\data --logpath C:\mongodb-win32-x86_64-2.4.6\log\mongodb.log --logappend --rest The command above must be run with administrator privileges. After that is done you can then use the net start and net stop commands provided by Hugo. – Ed Ost Aug 31 '13 at 19:41
3

From the given commands I think you're on Linux.

Start MongoDB:

$ sudo service mongod start
mongod start/running, process XXXXX 

Check the Status:

$ sudo service mongod status
mongod start/running, process XXXXX 

Stop MongoDB:

$ sudo service mongod stop
mongod stop/waiting 
ranafeb14
  • 437
  • 1
  • 7
  • 12
3

Using homebrew (recommended way):

To start:

brew services start mongodb-community

To stop:

brew services stop mongodb-community

nitin.agam
  • 1,949
  • 1
  • 17
  • 24
1

I simply did:

quit();

Please note I'm using mongo 3.0.

Mongo

Felipe Alarcon
  • 948
  • 11
  • 19
1

in the terminal window on your mac, press control+c

Shyamal
  • 21
  • 3
  • Someone downvoted this. It is, in fact, one of the ways to stop mongo according with mongo documentation. In a majority of situations this will not work, as mongo should be running in that terminal and not in background or as a demon, but "sometimes" this solution will work. When downvoting it is nice to explain why – TanisDLJ Aug 31 '17 at 15:17
0

I use this startup script on Ubuntu.

#!/bin/sh

### BEGIN INIT INFO
# Provides:     mongodb
# Required-Sart:
# Required-Stop:
# Default-Start:        2 3 4 5
# Default-Stop:         0 1 6
# Short-Description: mongodb
# Description: mongo db server
### END INIT INFO

. /lib/lsb/init-functions

PROGRAM=/opt/mongo/bin/mongod
MONGOPID=`ps -ef | grep 'mongod' | grep -v grep | awk '{print $2}'`

test -x $PROGRAM || exit 0

case "$1" in
  start)
     log_begin_msg "Starting MongoDB server"
         ulimit -v unlimited.
         ulimit -n 100000
     /opt/mongo/bin/mongod --fork --quiet --dbpath /data/db --bind_ip 127.0.0.1 --rest   --config /etc/mongod.conf.
     log_end_msg 0
     ;;
  stop)
     log_begin_msg "Stopping MongoDB server"
     if [ ! -z "$MONGOPID" ]; then
kill -15 $MONGOPID
     fi
     log_end_msg 0
     ;;
  status)
     ;;
  *)
     log_success_msg "Usage: /etc/init.d/mongodb {start|stop|status}"
     exit 1
esac

exit 0
Boris Ivanov
  • 4,145
  • 1
  • 32
  • 40
  • 2
    So you just kill mongoDB directly,right? I'm a beginner of MongoDB, is there any hurts to kill it? I know for SQLServer or Oracle, they will meet problems if we just kill them. – XiaoYao Aug 02 '12 at 09:54
  • to kill is -9 but -15 u send SIGNAL. – Boris Ivanov Aug 02 '12 at 10:14
0

Windows

In PowerShell, it's: Stop-Service MongoDB

Then to start it again: Start-Service MongoDB

To verify whether it's started, run: net start | findstr MongoDB.

Note: Above assumes MongoDB is registered as a service.

kenorb
  • 155,785
  • 88
  • 678
  • 743
0

Kindly take advantage of the Task Manager provided by your OS for a quick and easy solution. Below is the screengrab from/for Windows 10. Right-click on the highlighted process and select stop. Select start, if already stopped.

enter image description here

Please Note: Internally the commands are doing the same thing which you have to do manually using a GUI (Task Manager), provided by Windows/your OS. Though, this approach to be used for study/practice purpose to get started and you won't be blocked due to this.

Santhosh John
  • 648
  • 5
  • 14
0

To start sudo /etc/init.d/mongodb start

To stop sudo /etc/init.d/mongodb stop

Deepa Rokhade
  • 411
  • 4
  • 4
0

Could you try this please?

brew services stop mongodb/brew/mongodb-community
Saray Kim
  • 1
  • 3
-3

CTRL + C

on the windows command line

CodyBugstein
  • 21,984
  • 61
  • 207
  • 363
Vincent T.
  • 33
  • 2