MongoDB & pymongo: Step by Step

As I ventured into Lesson 4 in Udacity’s Data Wrangling with MongoDB, I really wanted to run the first script — inserting a record into the database — locally. I feel like I really damaged the sanctity of my files by installing, uninstalling, messing with permission, etc. for hours in all different locations in my computer. When I finally installed MongoDB, pymongo, and ran the script successfully… it seemed almost easy. So I wanted to share how I did it step by step. Note that I am on Mac OSX v 10.9.5.

First install pymongo. Open a terminal window and type pip install pymongo. I’m using Anacondas Python Distribution which comes with pip. This was the easiest part 🙂 On to installing MongoDB…

1. Download MongoDB file from here, unzip the folder, and move to your directory of choice. I simply put it in my home directory Users/frankCorrigan

2. Open terminal and cd into mongo and then into bin
cd mongodb-osx-x86_64-3.0.4/bin/

3. Make data directory to where data will be written
mkdir -p /data/db

Note: You may run into some permission issues. Best thing to do is check out StackOverflow.

4. At this point in the terminal I’m still in this directory
Users/frankCorrigan/mongodb-osx-x86_64-3.0.4/bin
and I want to run this mongod command like this
./mongod

5. If the last line says
waiting for connections on port 27017
then open a new terminal and type the command
./mongo

6. Open yet another terminal window and run the python script

def add_city(db):
    db.cities.insert({"name" : "Chicago"})

def get_city(db):
    return db.cities.find_one()

def get_db():
    from pymongo import MongoClient
    client = MongoClient('localhost:27017')
    db = client.examples
    return db

if __name__ == "__main__":
    db = get_db()
    add_city(db)
    print get_city(db)

After a second or two, this line should appear…
{u'_id': ObjectId('55998b5ffa699010f0937a98'), u'name': u'Chicago'}

And you are good! Remember to gracefully shutdown the server… go back to the window where you ran the ‘./mongo’ command and type ‘quit()’ and then go to the window where you ran the ‘./mongod’ command and type ‘control-c’.

This works for sure, but if I’m making ‘bad practice’ errors.. I’d love to hear it.

Leave a Reply

Your email address will not be published. Required fields are marked *