Apple,  Mac OS X,  Mac OS X Server,  SQL

Install and Setup mongodb on a Mac

I don’t write as much about what I do at my day job as I used to. I probably should, because it’s all still relavant to my older readers. One example of that is that I have published a lot of articles on MySQL and sqlite. However, more and more of my development efforts use native json. I’ve slowly fallen in love with mongodb for this reason – I can have a local database that is fast, that stores data in native json. That makes my transactions cheaper when it’s time to read and write for databases. If I have to regex to put information in sql and then take it back out, it’s just… more work. And a more expensive transaction at runtime.

Mongo doesn’t come pre-installed on a Mac, though. Luckily, installation is a one-liner with homebrew, though:

brew install mongodb-atlas

Alternatively, install it manually. The package can be downloaded at https://www.mongodb.com/try/download/community and then extract the tgz and tarball into an actual directory. Next, move the directory to where you want it to live. I’ll use /usr/local/mongodb in the following example:

sudo mkdir /usr/local/mongodb

Next, create a data directory. I picked up /data/db in their docs long ago and still just use that, as follows:

sudo mkdir -p /data/db

Then set the appropriate permissions for the data directory:

sudo chown -R id -un /data/db

Now let’s fire up the daemon (assuming you put Mongo into the /usr/local directory):

/usr/local/mongodb/bin/mongod

Now run the local shell – old school shell being (note that there’s a newer shell as well, which is far more lovely to work with):

/usr/local/mongodb/bin/mongo

Use show dbs as the command to show the databases running:

show dbs

Then use db to show the current one. Alternatively, use the shell to show collections:

show collections

Or switch databases with the use verb. Like if you had one named daneel it would be as follows:

use daneel

Or run a javascript from there (although you can do this with an -f flag when invoking the shell in the first place:

load("myScript.js")

To exit the shell, simply use a quit command with no parameters (and notice the load and quit commands look more like javascript – because they are):

quit()

Assuming you are still running the mongod daemon in its own window, just control-c to kill it. I usually run mine interactively on my testing machine, but if it’s to be persistent on a Mac you’d wanna’ create a LaunchDaemon to daemonize it…