4/13/2015 - 9:07 PM


###mongodb quick CLI reference

db backup and restore

from any directory on host machine, export entire db

$ mongodump -db myDatabaseName

now copy the /dump folder to destination machine. from the destination machine:

$ cd ~/path/to/dump/folder
$ mongorestore

db wipe

launch mongo into your db

$ mongo myDbName

in mongo, call dropDatabase to erase db permanently

> db.Dropdatabase()

db query

launch mongo into your db

$ mongo myDbName

show all collections inside this db

> show collections

show all databases on this computer

> show dbs

show all items in a collection, format them pretty

> db.collection.find().pretty()

search for items in a collection that match a specific query, format results pretty

> db.collection.find({key:"val"}).pretty()

mongodb setup and debug

install mongodb with Homebrew

Install Homebrew (mac only)

$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Install mongodb

$ brew install mongodb

Set up launchctl to auto start mongod

$ ln -sfv /usr/local/opt/mongodb/*.plist ~/Library/LaunchAgents

/usr/local/opt/mongodb/ is a symlink to /usr/local/Cellar/mongodb/x.y.z (e.g., 2.4.9)

You can use launchctl to start and stop mongod

$ launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist
$ launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist

You can also more conveniently use brew to start, stop, and verify service status

$ brew services list | grep mongodb
$ brew services start mongodb
$ brew services stop mongodb

reinstall mongodb

uninstall mongodb

$ brew uninstall mongodb

update homebrew

$ brew update

install mongodb

$ brew install mongodb

mongodb startup/launch

To have launchd start mongodb at login:

$ ln -sfv /usr/local/opt/mongodb/*.plist ~/Library/LaunchAgents

Then to load mongodb now:

$ launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist

to fix "ERROR: dbpath (/data/db) does not exist"

$ sudo mkdir -p /data/db/
$ sudo chown $USER /data/db
$ mongod --dbpath /data/db