Tuesday, December 3, 2013

Getting started with Mongo DB

Once you are suitably convinced you do need a document oriented database for persisting your data, you can get started with using mongo db, the very popular document oriented database of our times.

While mongo db is the most similar to RDBMS as compared to other NOSQL databases, but there are a few surprising things you should know about mongo.

To recount a few:

Objects and arrays of objects can be used interchangeably in mongo db insert syntaxes

hence following is quite valid

db.mytablecoll.insert({name: ’Ganesh Ghag’, dob: new Date(1973, 6, 18, 18, 18), loves[’grape’,’watermelon’], hometown: 'Thane', gender: ’m’});


Update without Set

In its simplest form, update takes 2 arguments: the selector (where) to use and what field to update with.
db.mytablecoll.update({name: ’Ganesh Ghag’}, {hometown: 'Thane West'})
will replace the entire object aka row with {hometown: 'Thane West'}

to selectively update only one attribute of the row, you will need to use Set
db.mytablecoll.update({name: ’Ganesh Ghag’},  {$set: { hometown: 'Thane West'} } )


Multiple Updates surprise

The final surprise update has to offer is that, by default, it’ll update a single document.
so the following will only update the first row fulfilling the update criteria
db.mytablecoll.update({name: ’Ganesh Ghag’},  {$set: { hometown: 'Thane West'} } )

to ensure upsert functionality you will need a 3rd parameter "upsert" as true as shown below
db.mytablecoll.update({name: ’Ganesh Ghag’},  {$set: { hometown: 'Thane West'} }, true )

and to ensure all possible rows in collection are updated you need to set a fourth parameter "multiple" as true
db.mytablecoll.update({name: ’Ganesh Ghag’},  {$set: { hometown: 'Thane West'} }, true, true )


There is no "join" syntax in mongo db

All many to one and many to many relations are modelled using arrays of objects or embedded documents

Transactions in mongo

Mongo DB does not support transactions in classical sense, but has operators for atomic operations like $where and also 2-phase commit based manual transaction modelling

Support for geo-spatial queries

Mongo DB has direct support for geo-spatial indexex. This allows you to store x and y coordinates within documents and then find documents that are $near a set of coordinates or $within a box or circle.


If above mongo DB surprises are enough to keep you awake, wondering, at night, please visit Little Mongo DB book for an introduction to mongo db.



Cheers!





No comments: