Creating a MongoDB Database Locally

posted in: Uncategorized | 0

For the first part you will need to setup MongoDB 2.6+ using Homebrew in Mac OS X and second configure a database for building a REST API using NodeJS on a local machine. The second part should be similar for Linux and Windows with exceptions to the dbpath, mongod.conf, and mongo.log locations.

 

Setup

You will need to have Homebrew installed. To learn how to install Homebrew read the Homebrew Wiki.

Once you have Homebrew installed. Open a terminal window and enter the following:

Once MongoDB has finished installing open /usr/local/etc/mongod.conf and make a note where the default database is going to be located for future reference, the dbpath. You will need this location later. Of course you can change the location to anywhere else.

 

Configure

In MongoDB version 2.6+, the format of mongod.conf is in YAMLformat. You can copy and paste the following into mongod.conf to update it to YAML format:

For more on the configuration options see MongoDB Configuration File Options and MongoDB Network Exposure and Security.

In the following next steps you will need two (2) terminal windows open.

  1. In one terminal window enter (note that the port is an optional parameter, the default port is 27017). If you changed the path in dbpath, changed it below:
  2. In the second terminal window enter mongo. This give you access to the database. If you enter show dbs in mongo, it will list database name: admin (empty).
  3. Next enter the following to create the database administrator user for the admin database:
    To quit mongo enter either exit or press control + c.

    Reference: MongoDB Enable Authentication after Creating the User Administrator

  4. Now go back to the first terminal window and press control + c to terminate mongod. Then start mongod again by entering:

  5. Now it is time to add a user and to create a new database:

    For more on db.createUser see MongoDB db.createUser()

  6. Afterwards it should have created a new user and a database called mydb. You can test it out by doing:

    It should display WriteResult({ “nInserted” : 1 }).

You can also use Robomongo (Mac OS X, Windows, Linux) to check if the database has correct information stored.

Reference: Getting Started with MongoDB