Skip to content

Instantly share code, notes, and snippets.

@jmsaavedra
Last active January 24, 2017 01:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jmsaavedra/9a95eab2de4e3235e7ef to your computer and use it in GitHub Desktop.
Save jmsaavedra/9a95eab2de4e3235e7ef to your computer and use it in GitHub Desktop.
mongodb cli quick reference + setup guide

###mongodb quick CLI reference

db backup and restore

from any directory on host machine, export entire db

$ mongodump -db myDatabaseName #OSX
$ mongodump --db myDatabaseName -o C:\Users\someuser\Desktop #win

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment