How to run a command at startup

I want to automatically start my MongoDB Server at startup. The command for it is

mongod --dbpath="/Users/prateek/Desktop/Mongo Database"

How do I configure this in Mac OSX El Capitan?

Note - I have installed MongoDB using Homebrew


Solution 1:

Create a file named org.mongod.user.plist in ~/Library/LaunchAgents with the content:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>org.mongod.user</string>
    <key>ProgramArguments</key>
    <array>
        <string>mongod</string>
        <string>--dbpath=/Users/prateek/Desktop/Mongo Database</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
</dict>
</plist>

This requires that mongod is in your path.

If mongod is not in your path, use the whole path in the first string of the ProgramArguments array (e.g. /usr/local/Cellar/mongodb/3.2.1/bin/mongod)

If you need stdout or stderr (which can be helpful if something fails) add the following in the dict section of the plist:

    <key>StandardErrorPath</key>
    <string>/tmp/org.mongod.user.stderr</string>
    <key>StandardOutPath</key>
    <string>/tmp/org.mongod.user.stdout</string>

Load and start mongod with:

launchctl load ~/Library/LaunchAgents/org.mongod.user.plist
launchctl start org.mongod.user

To connect to your MongoDB database enter:

mongo localhost

Again this requires that mongo is in your path. Otherwise use the complete path (e.g. /usr/local/Cellar/mongodb/3.2.1/bin/mongo).