Thursday, 18 August 2016

Installing MongoDB in Mac

Background

Sometime back I had written a post on MongoDB. Installation and basic syntax in Windows - Getting Started with MongoDB . This post is starting of series of posts on MongoDB. In this post we will see installation and configuration of MongoDB in Mac.

Installing MongoDB

  • Go to MongoDb download center and download the tgz of the latest build. Your OS should already be selected and you should see the download link.
  • You can also install MongoDB using homebrew
    • brew install mongodb  (To install the MongoDB binaries)
    • brew install mongodb --with-openssl (To install the MongoDB Binaries with TLS/SSL Support)
    • brew install mongodb --devel  (To install the latest development release)
  • Once you have downloaded that tarball you can unpack it using following command - 
    • tar xvf mongodb-osx-ssl-x86_64-3.2.9.tgz
  • Once you have unpacked it navigate to that folder and then into bin folder inside it. Here you will see list of programs. There are two programs here of out interest - 
    • mongo : This is the mongo shell used to connect to the mongo DB.
    • mongod : This is the actual server.
  • That's it your mongo db is installed and ready to be run.
NOTE : MongoDB by default stores its data in directory "/data/db". So make sure this directory is created with necessary permissions. 
  • sudo mkdir -p /data/db
  • sudo chmod -R 777 /data/

If you want to give a custom path you can give it when you start mongodb - 
  --dbpath arg                          directory for datafiles - defaults to "/data/db"
Eg.
  • mongod --dbpath /data/mydb

Running and connecting MongoDB

  • To run MongoDB server go to bin directory and start mongod program.
    • ./mongod
  • This should start your mongodb server listening on default port 27017.
  • To see all mongod configuration options you can type - 
    • ./mongod --help



Once mongodb is up you can try connecting to it using mongo shell.
You can start mongo shell by
  • ./mongo
You can also see incoming connection in your server console -
  • 2016-08-18T22:34:27.315+0530 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:56356 #1 (1 connection now open)
     
Once you are connected you can try following operations - 
  • use mydb
  • db
  • show dbs
  • db.testCollection.insert({"Name":"John"})
  • show collections
  • db.testCollection.find()
 That's it for the basic of installing Mongo DB on your Mac. To avoid always going till bin to execute your programs you can do either of of the follwing -
  1. Add you path to bin to your PATH and export it. OR
  2. Add all these binaries to /usr/local/bin/ by
    • cp * /usr/local/bin
  3. You can verify it by wither running - 
    1. which mongod OR
    2. mongod --help

Related Links

No comments:

Post a Comment

t> UA-39527780-1 back to top