How to stop mongo DB in one command - mongodb

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?

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
Find PID of mongod process using $ top
Kill the process by $ kill <PID> (the Mongo docs have more info on this)
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.

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.

mongod --dbpath /path/to/your/db --shutdown
More info at official: http://docs.mongodb.org/manual/tutorial/manage-mongodb-processes/

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

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 :-)

Use mongod --shutdown
According to the official doc : manage-mongodb-processes/
:D

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

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.

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

One liners to start or stop mongodb service using command line;
To start the service use: NET START MONGODB
To stop the service use: NET STOP MONGODB
I use this myself, it does work.

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

Using homebrew (recommended way):
To start:
brew services start mongodb-community
To stop:
brew services stop mongodb-community

I simply did:
quit();
Please note I'm using mongo 3.0.
Mongo

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

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

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.

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.
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.

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

CTRL + C
on the windows command line

Related

Mongodb How can I stop shutdown one of instances

I'm a newbie to Mongodb. I installed Mongodb 3.4 and setup two config files each config has different port and share a same ip address. How can I shut down instance in mongoA.conf file. Try to use command "sudo service mongod stop" But it doesn't know which config file to stop the service. Thanks in advance
start two instances Mongodb config files:
mongod --config /etc/mongoA.conf
mongod --config /etc/mongoB.conf
You can find PID of mongod port. Then kill process on that PID.
To find all PID mongod, type:
# ps -aux | grep mongod
You will see on console:
root 28035 0.9 18.5 5319648 2992608 ? Sl Apr06 1493:14 mongod --config /etc/mongoA.conf
Then kill process on this PID:
# sudo kill -9 NUMBER_PID
On above example, NUMBER_PID is 28035.
On OSX ps -alx will give the same list of processes.
If you allow kill to send the default TERM signal by not using -9 explicitly it will allow the database to catch the TERM signal and shutdown cleanly.

How to list all running mongod processes?

Does mongod have a cli command similar to forever list that will show all running mongod processes?
In mongod --help I could only find --shutdown option:
--shutdown kill a running server (for init scripts)
Ok, we can terminate a running server. But how may we see running servers?
In Git Bash:
$ ps -alW | grep mongod
4592 0 0 4592 ? 0 12:47:09 C:\Program Files\MongoDB\Server\3.2\bin\mongod.exe
This is a OS way using ps. Still do not know if mongod has special command for that.
Also here https://askubuntu.com/questions/182137/how-do-i-know-which-processes-are-running-and-who-own-the-process
I think you are looking for mongostat

How to stop mongod after "unkown instance" error

After running two mongodb instance, I can't stop mongod service. After executing:
$ sudo service mongod stop
Stop: Unkown instance
I know that this question have been asked but they are looking for how to avoid this error and I am looking for how to actually stop the mongod service after getting this error...
Running sudo service mongod start twice doesn't start mongo twice. It should be an idempotent operation meaning it only has an effect the first time if mongo wasn't running. Any attempts to start it afterwards will do nothing.
Your message of Stop: Unkown instance will mean that it couldn't find any running Mongo processes to stop.
To verify Mongo isn't running, try running
sudo ps aux | grep -v grep | grep mongo
If that returns nothing, then you don't have any mongo processes running.
I usually just kill the process. Works every time.
killall -9 mongod

MongoDB: ERROR: child process failed, exited with error number 14

I run MongoDB on Mac:
Shave:mongodb_simple Logan$ ./bin/mongod -f conf/mongod.conf
about to fork child process, waiting until server is ready for connections.
forked process: 5110
ERROR: child process failed, exited with error number 14
Is that because I shutdown it in wrong way?
You started and probably shutdown mongo in the wrong way.
1. TO START MONGODB
To start mongo in the background type: mongod --dbpath /data/db --fork --logpath /dev/null.
/data/db is the location of the db. If you haven't created one yet => type: mkdir /data/db
--fork means you want to start mongo in the background - deamon.
--logpath /dev/null means you don't want to log - you can change that by replacing /dev/null to a path like /var/log/mongo.log
2. TO SHUTDOWN MONGODB
Connect to your mongo by typing: mongo and then use admin and db.shutdownServer(). Like explain in mongoDB
If this technique doesn't work for some reason you can always kill the process.
Find the mongodb process PID by typing: lsof -i:27017 assuming your mongodb is running on port 27017
Type kill <PID>, replace <PID> by the value you found the previous command.
Check the ownership of the file /tmp/mongodb-27017.sock
It should be mongod. I got same error since it was root:root
For me it was ulimit issue, mongo could not open too many files.
Used ulimit -n 10000.
However as a generic pointer look into mongo logs file, they will tell where to look further. Generally the logs file are in /var/log/mongo.log but look into your mongo config file.
It's because you haven't configured your mongod instance correctly in the config file that you passed to the -f option.
Revisit your config file and make sure eveything is configured correctly.
By changing owner to mongodb for all files under /var/lib/mongodb/ it started working for me:
chown mongodb:mongodb -R /var/lib/mongodb/
This worked for me:
run in terminal
sudo rm -rf mongod.lock
export LC_ALL=C
then
sudo mongod --fork --config /xxxx/xx/mongod.conf --logpath /xxx/log/mongodb/mongodb.log
with me I remove file: /tmp/mongodb-27017.sock
then restart mongod
Just run this and start mongod
rm -f /tmp/mongodb-27017.sock
systemctl start mongod
Check if the mongod is running with pgrep mongod or ps -aef | grep mongod or systemctl status mongod
Stop and restart it to check if the issue gone
if you start mongod with mongod -f /etc/mongod.conf kill it with pkill -9 mongod then start it with mongod -f /etc/mongod.conf
fi you run it a service, use systemctl restart mongod to restart it.
If restart not works, figure out the issue by the /var/log/message and /var/log/mongodb/mongod.log file.
use tail -f /var/log/message and tail -f /var/log/mongodb/mongod.log to check the output when your action.
for example:
1.
Failed to unlink socket file /tmp/mongodb-27017.sock Operation not permitted
delete the sock file with `rm`
2.
WiredTiger error (13) [1596090168:830936][25997:0x7fe22f208b80], wiredtiger_open: __posix_open_file, 672: /data/mongo/WiredTiger.turtle: handle-open: open: Permission denied Raw: [1596090168:830936][25997:0x7fe22f208b80], wiredtiger_open: __posix_open_file, 672: /data/mongo/WiredTiger.turtle: handle-open: open: Permission denied
Failed to start up WiredTiger under any compatibility version
Reason: 13: Permission denied
check the file permission or owner with `ls` then change to the wright permission with `chmod` or right owner with `chown`
I had this same issue, but mine was the system clock being off so my SSL cert was technically invalid. Changing to the current date and time worked date --set "<DD M Y H:M>" Only found this by looking at the mongodb log
I encountered this issue on a GCP managed Compute Engine instance.
As this is the top answer on a Google search for the issue, I'll include what worked for me, and is a documented bug as per MongoDB (jira-link)
On linux systems, if the user running mongod does not have a locale set or the locale is misconfigured, mongod fails to start printing a stack trace.
The issue can be resolved by combining a few steps:
Install the required language packs (ref):
sudo apt-get install language-pack-XX
Run update locale (ref):
sudo update-locale
Restart your session, and check the same mongo command again
IFF the above doesn't work (it didn't for me), just manually add the following to the file at /etc/default/locale (ref):
LC_ALL=en_US.UTF-8
LANG=en_US.UTF-8
Just to admire the absence of those persistent warnings about LC_ALL not being set, run the following:
sudo dpkg-reconfigure locales
That's all, your MongoDB instance should be good to go now!
In my mongodb setup, in order to retain a specific version of mongoDB inline to existing servers and also to avoid having binary files placed under root disk, i changed the path of all mongo binaries in a different directory. i had to use rpm option instead of yum option (as yum installs only the latest version despite of mentioning the specific version).
rpm -ivh --prefix=/apps/mongodb /apps/mongo_rpm_packages/mongodb-org-*.rpm
Note: The default path where the binaries will be placed is /var/lib/mongo.
This approach does not either allow required permission for mongod user or its not provisioned properly and hence, i changed user and group in mongod.service file to root user and managed to successful start the process using:
service start mongod
Use --shutdown
mongod --shutdown
Then
service mongod restart
It work!
https://docs.mongodb.com/manual/tutorial/manage-mongodb-processes/#use-shutdown

Mongo is letting me down

I've been trying to run mongo on my system, but I just doesn't want to start. I've installed mongodb with brew. Both mongo and mongod are on my system and I can use them. But the mongod process won't start.
These are the steps I'm taking after I installed mongo on my system with brew.
$ mongod
all output going to: /usr/local/var/log/mongodb/mongo.log
$
It seems mongod is closing directly, because I don't see any process running and it gives me the dollar sign back again. Thereby there's no rotating icon in my terminal, so it isn't running.
If I open a new window in the terminal after running the above command, I'm getting this error:
$ mongo
MongoDB shell version: 2.4.3
connecting to: test
Thu May 23 12:22:09.314 JavaScript execution failed: Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:L112
exception: connect failed
$
This output is a logical error seen from the fact mongod didn't do a thing. But when I run this:
$ ps -ef | grep mongod
501 99123 15827 0 12:24PM ttys001 0:00.00 grep mongod
$
So I'm not sure or it's running or not.. You guys know a solution for this? Because I can't figure out what I'm doing wrong..
update
I've tried to change the db path and that works partially. I'm now able to run mongod command, but I need to specify the dbPath even though I have the dbPath changed in the config file.
$ mongod --dbpath ~/data/db/
And when I try to run mongod by itself, it won't run..
$ mongod
all output going to: /usr/local/var/log/mongodb/mongo.log
$
I don't have a working solution, but from your output, it seems like mongod is running daemonized. You could try setting the 'fork' option to false (or uncommenting it) in /usr/local/Cellar/mongodb/2.4.x-x86_64/mongod.conf and running mongod with the -v / --verbose flag to see if that gives you more details.
Also, are you sure you're actually using the homebrew version of mongo and not some previously installed version? You can check which mongod is used by running:
➜ ~ which mongod
/usr/local/bin/mongod
And the following to see if that's indeed the version that got installed using homebrew:
➜ ~ ls -l /usr/local/bin/mongod
lrwxr-xr-x 1 user admin 41 21 mrt 22:06 /usr/local/bin/mongod -> ../Cellar/mongodb/2.4.x-x86_64/bin/mongod
The default data directory is /data/db. In order to have that work by default you need to do two things:
sudo mkdir -p /data/db
sudo chown `whoami` /data/db