MongoDB - Getting started

How to setup MongoDB on Mac?

This guide is to help you install latest MongoDB on mac and get started.

 

1. Where to Download From?

Please go to http://www.mongodb.org/downloads page and download the latest version suitable for mac.

$ tar xzf mongodb-osx-x86_64-2.4.6.tgz
$ sudo mv mongodb-osx-x86_64-2.4.6.tgz /usr/local/mongodb

2. How to start the server?

$ mkdir ~/mongo_db
$ mongod --dbpath ~/mongo_db --rest --jsonp

You can also start server by simply executing
$ mongod

However, below are the most commonly used parameters for quick setup and use.

--dbpath determines the location where the database will be created.
--rest parameter is necessary for enabling RESTful API
--jsonp is needed enabling javascript callback when writing front end AJAX calls.

3. How to test your setup?

Open a new terminal and run below command to open mongodb CLI.

$ mongo

Here are simple and often used commands - 

To see the list of databases - 

> show dbs;
local    0.078125GB

To create/use a database named "school" (MongoDB creates an actual DB only when you start inserting data. There is no other separate step of database creation) -

> use school;
switched to db school

MongoDB has concept called collection, which is little analogues to standard RDBMS tables.
Now to insert data into a collection called "student", simply execute -

> db.students.save({"firstname": "nilesh","lastname": "mahajan","rollnumber": 101});

To view the content of a collection -

> db.students.find()
{ "_id" : ObjectId("52536af24e0b01d0863bc93d"), "firstname" : "nilesh", "lastname" : "mahajan", "rollnumber" : 101 }

MondoDB automatically inserts an _id attribute if the input object doesn't have it.

If you go to, http://localhost:28017/
you can see a control panel with additional information, list of commands etc.

Also, if you hit  http://localhost:28017/school/students/
you can see retrieve your collection information. Please note the trailing '/' at the end of above URL, otherwise mongodb will not show you any error. But it will return 0 objects always.

And finally, to clear the collection -

> db.students.remove()

This should be easy to get you started with mongodb setup and some basic CRUD operations.