MongoDB – Quick Start Installation and Usage

2 weeks back I attended yet another RHoK Melbourne event and ended up working on a project with NodeJS & MongoDB: both unfamiliar territories for me and thought it would be a good opportunity to create a quick start guide: here is the MongoDB one

Installing and Running the Server

  1. Get the binaries on the download page (http://www.mongodb.org/downloads) and get the necessary download for your platform (Windows/Linux/OS X/Solaris). Following commands will be based on OSX but similar actions can be one on other platforms
  2. In a terminal, navigate to where you downloaded the package and extract it
    cd ~/Downloads
    tar -zxf mongodb-osx-x86_64-2.4.8.tgz
  3. Create a folder to store your database
    cd mongodb-osx-x86_64-2.4.8
    mkdir db
  4. Start the server specifying the folder created
    bin/mongod --dbpath=db

Terminology coming from the typical relational database world

Relational Database MongoDB
Database / Schema Database
Table Collections
Row Record
Field / Column Field

Quick start of the MongoDB Shell

  1. Connect to the server
    Navigate to the folder where the files are extratcted, run the mongo Javascript shell  (which has tab completion)

    cd ~/Downloads/mongodb-osx-x86_64-2.4.8
    bin/mongo
  2. List / show databases
    show dbs
  3. Select a database (no need to created a database)
    > use unicorn
    switched to db unicorn
    > db
    unicorn
  4. Show collections (tables)
    show collections
  5. Inserting a record (row in a table)Collections do not need to be initialised, they are auto generated.
    Below shows the output of the Mongo shell. system.indexes contains indexes for collections

    > show collections
    > db.unicorns.insert({name: 'Aurora', 
       gender: 'f', weight: 450})
    > show collections
    system.indexes
    unicorns

    Mismatched fields

    db.unicorns.insert({name: 'Aurora', gender: 'f', weight: 450})
    db.unicorns.insert({name: 'Leto', gender: 'm', 
        home: 'Arrakeen', worm: false})

    Arrays

    db.unicorns.insert({
        name: 'Solnara', 
        loves:['apple', 'carrot', 'chocolate']})
  6. Listing / Querying records
    > db.unicorns.find()
    { "_id" : ObjectId("52b65132eb122da0e6dd19a9"), "name" : "Aurora", "gender" : "f", "weight" : 450 }
    { "_id" : ObjectId("52b6519127026146f128de90"), "name" : "Leto", "gender" : "m", "home" : "Arrakeen", "worm" : false }

    Items have _id auto generated. No need to set an auto increment field.

    Filtering and field selection

    db.collection.find(
       {andedFilters}, 
       {fieldWith1AsShow0asHide}
    )

    Search by name and show only name and worm  fields

    > db.unicorns.find({name: 'Aurora'}, {name: 1, worm:1, _id: 0})
    { "name" : "Aurora" }
    > db.unicorns.find({
        $or: [{name: 'Aurora'}, {'name': 'Leto'}]}, 
       {name: 1, worm:1, _id: 0}
    )
    { "name" : "Leto", "worm" : false }
    { "name" : "Aurora" }

    Paging and Limiting results

    db.unicorns.find().skip(1).limit(2)

    Record Counting

    db.unicorns.count()
    db.unicorns.find({'name' : 'Aurora'}).count()

    Distinct

    db.unicorns.distinct('name')
    db.unicorns.distinct('name', 
       {$or: [{'name' : 'Leto'}, {'name':'Aurora'}]})
  7. Query Selectors
    1. Comparison:
      1. $gt / $lt ($gte / $lte): Greater/Less than (or equal).
      2. $ne, $in / $nin: Not equal. In / Non in
    2. Logical: $or, $and, $not, $nor
  8. Updating:
    Update first matching record

    db.unicorns.update(
      { name: 'Aurora' }, 
      { $set : { weight: 10 } } 
    )

    Update all matching records

    db.unicorns.update(
      { name: 'Aurora' }, 
      { $set : { weight: 10 } },
      { multi: true }
    )

    Update matching record but insert if doesn’t exist

    db.unicorns.update(
      { name: 'Roooooodles' }, 
      { $set : { weight: 10 } } ,
      { upsert: true }
    )
  9. Deleting:
    Deleting all records:

    db.unicorns.remove()

    Delete all matching records

    db.unicorns.remove({name: 'Aurora'})

    Delete only first matching record

    db.unicorns.remove({name: 'Aurora'}, true)
  10. Drop collection
    db.unicorns.drop()

Other Considerations

  1. No joins. But has embedded documents
    > db.unicorns.insert({name: 'Aurora', gender: 'f', weight: 1450, owner: {'name': ['You', 'Me']}})
    > db.unicorns.find({'owner.name': 'Me'}, {'name': 1, 'owner.name': 1, _id: 0})
    { "name" : "Aurora", "owner" : { "name" : [ "You", "Me" ] } }

Further References

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s