15 Mar 2014

Handling Blobs in MongoDB

When we talk of database one question that arises is how do we store large objects in MongoDB, and when i say large objects i am necessarily referring to any data that is larger than 16MB, can also be referred most commonly as Blobs  (remember a document size in MongoDB cannot be larger than 16MB). The answer is GridFS (Grid File System).

Now as we know that any document cannot be larger than 16MB of size in MongoDB, what GridFS does is that it breaks a large file into chunks and stores them into two different collections. One collection is called the chunks collection and the other as file collection.
How MONGODB saved BLOB using GridFS

Lets now see how we actually do save a simple large file in mongodb using java and how does it gets saved in the mongodb instance.

I am going to create a very simple java file which will save a large zip file using gridfs

package course;

import java.io.FileInputStream;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSInputFile;

public class GridFSExample {
public static void main(String[] args) throws UnknownHostException {
	MongoClient client = new MongoClient(new MongoClientURI("mongodb://localhost"));
	DB db = client.getDB("mycollection");
	FileInputStream fis = null;
	GridFS docs = new GridFS(db, "docs");
		fis = new FileInputStream("D:/_handouts/final_exam.zip");
	}catch (Exception e) {
	GridFSInputFile doc = docs.createFile(fis, "final.zip");
	BasicDBObject meta = new BasicDBObject("description","Test document");
	List tags = new ArrayList();
	meta.append("tags", tags);
Lets me try to explain the code a little, although its quite self explanatory. In this example the only difference that you would note while storing a large file is using GridFS and GridFSInputFile API's. Also you can set some meta tag that you want to define for the document.

Once i have done it let me try and show you how did it get stored in the MongoDB. Let us see what all gets created in my DB mycollection
Figure 2: Console screenshot showing collections in DB mycollections
Now if you note that there is no collection as docs that got created, instead there are docs.files and docs.chunks that was created. Lets get deeper, what are the contents of the docs.chunks and docs.files contents

Figure 3: Screenshot showing the contents of docs.files collection
Lets now see whats in the docs.chunks collection
Figure 4: Screenshot showing contents of docs.chunks collection

Now lets drive the analogy of the contents of the docs.files and docs.chunks collection, if you see the metadata and the basic details of the file got into the docs.files collection, however the real content of the blob, actually got stored in the docs.chunks collections as multiple documents with the same value of files_id and a counter "n", which tells how the chunks should be assembled while fetching the file back.

Hope this would make your life simpler now dealing with large data in mongodb.

20 Jan 2014

Create REST web service using NodeJS & MongoDB

In this article we will learn how to create a web application which has REST web services to create, get and delete user data.

First lets identify the different modules we are going to use for this example in NodeJS
a) Mongoskin - Module to connect and operate on MongoDB collection needed for this example
b) Restify - Module to offer basic operations / functionality needed to create REST endpoints and handlers

So lets first detail out how we are going to create a package for the npm for this project, here is how the package.json for this project would look like

  "name": "RestWebApp",
  "version": "0.1.0",
  "description": "RestWebApp",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified! Configure in package.json\" && exit 1"
  "repository": "",
  "keywords": [
  "dependencies": {
   "restify": "*",
   "mongoskin": "~0.6.0"
  "author": "Anup Gaurav",
  "license": "MIT",
  "readmeFilename": "README.md"
Important things to note here is that we have added both the needed dependencies in our "dependencies" section of the package.json. Fairly we can skip with specifying version for the modules, however i have defined the version for mongoskin.

In this example we will also try to cover briefly as to how to make the code / project structure modular, see the screen shot attached below
Figure 1: Project structure for the Rest application project
 If you see in detail the project structure, you will note one thing new, i.e. having the routes folder, what i am intending to do here is to make things modular, so i have created this file user.js which will have all the operations on the user collection rather than all being in the app.js. I will keep app.js just to initiate and have the REST endpoints defined within it. Lets lets first get started with user.js, where we will define all three data operations on the collection,
a) AddUser - To add a new user in the collection MyUsers for this application
b) GetUser - To get user document for a specific email id
c) RemoveUser - To delete user document from a collection matching a specific email id

Now let me put the contents of user.js file and then we will discuss the contents of the same

exports.addUser= function(req, res, next){
 if (!req.body || !req.body.userName) return next(new Error('No data provided.'));
  first_name: req.body.firstName,
  last_name: req.body.lastName,
  age: req.body.age,
  active: false
  }, function(error, appUser){
   if (error) return next(error);
   if (!appUser) return next(new Error('Failed to save.'));
   console.info('Added %s with id=%s', appUser.first_name, appUser._id);

exports.getUser= function(req, res, next){
 if (!req.params.email) return next(new Error('No input parameter provided.'));
  email:req.params.email}, function(error, appUser){
   if (error) return next(error);
   if (!appUser) return next(res.send(404));
   console.info('Found %s with email=%s', appUser.first_name, appUser.email);

exports.removeUser= function(req, res, next){
 if (!req.params.email) return next(new Error('No data provided.'));
  email:req.params.email}, function(error, appUser){
   if (error) return next(error);

Now lets understand this code better,  we have actually made some method definitions that needs to be exported (thats why we have used exports) where ever called.
Now each of the these function definitions start with function(req, res, next), where req is the http request object, res is http response object and next is a router control being offered by node js to call the next matching route when called.

Secondly you would question about the code within each function, we have actually called standard mongodb operations using mongodb standard functions, however there are few references that we have defined in the app.js and used it here, say how we have referenced the collection and DB on which we want to operated, in this file we have referenced it by req.db.appUser, but the same has been defined in the app.js file. When you would see the code of app.js, you would probably be able to relate.

Also to not is that we have used standard operators http request object req to get the either from the JSON object being passed in request body(In case of addUser) or request parameter being passed in the GET and DELETE operation.

Now lets also see the app.js code which would make the code complete and give us better clarity as to how the entire piece is working, here is the app.js code

var restify = require('restify');
var mongoskin = require('mongoskin');
var user = require('./routes/user');

// Server
var server = restify.createServer({
  name: 'myapp',
  version: '1.0.0'

//DB Connection
var db = mongoskin.db('mongodb://localhost:27017/RestApp?auto_reconnect', {safe:true});

//Define References
server.use(function(req, res, next) {
 req.db = {};
 req.db.appUser = db.collection('MyUsers');

//Define Parsers

// Define POST operation on AppUser Collection
server.post('/user', user.addUser);
server.get('/user/:email', user.getUser);
server.del('/user/:email', user.removeUser);

server.listen(80, function () {
  console.log('%s listening at %s', server.name, server.url);

Now lets go over this code line by line.

In the first two lines we have imported the required dependencies for mongoskin and restify modules.,
The third line of code has a import to the user module we created with the db function we have defined, moving along we have then created a restify server using the restify module that we imported above.
Further using the mongoskin module we connected to the mongoDB.

Now comes a very important section where we have asked the server to use some referenced such as
req.db.appUser = db.collection('MyUsers');

which states that when ever we call req.db.appUser, i actually mean to refer to the collection 'MyUsers' in the mongoDB connection i made above. Post this we have defined the parsing modules to be used by the server.

Now something very important and yet very simple using the restify module being imported. We have defined 3 endpoints , one for POST, one for GET and the last one for DELETE HTTP operations that we wanted to process. Point to note here is that we are using same/similar URL patterns of the request, but distinguishing them with the HTTP verb being used, which is how a REST web service end point should be coded and we have done the same way adhering to best practices for REST web services.

At last we start the server and start listening to port 80.
You can now go ahead and test the application using a REST client, please note that while testing the POST request, make sure you set the content-type as application/JSON in the header before sending the request.

Just test it out and you will have your first REST web services using NodeJS and MongoDB working.    

18 Jan 2014

Using $push, $pop, $pull, $pushAll, $pullAll & $addToSet operators in MongoDB

As documents can have arrays inside it and in more practical scenarios you will realize in most of the practical scenarios you would use arrays inside documents that you store and update in a MongoDB.

However using normal update method from MongoDB you can update elements or values inside a document.

Let't take an example, say i have a document in a collection called testarray
{ "_id" : "1", "test" : [  1,  2,  3,  4 ] }

Now say i want to update the 2nd element in the array and set the value as 5 instead of 2, i will do something like
> db.testarray.update({"_id":"1"},{$set:{"test.1":5}})

which would result and set the document now to be
{ "_id" : "1", "test" : [  1,  5,  3,  4 ] }

Now say we need to add another element at the end of the document, one way is
>  db.testarray.update({"_id":"1"},{$set:{"test.4":5}})

Now via this statement i am asking the document to be updated and value 5 to be set at 5th location in the array, the resulting document would be
{ "_id" : "1", "test" : [  1,  5,  3,  4 ,5] }

Now we can think of and do a lot of manipulation here but we first need to be aware what is the length of the array and in case of deleting something, we can set the value at the position as null but not squeeze the size of the array.

To deal with such scenarios and to deal with array manipulation in a document more efficiently, we have  $push, $pop, $pull, $pushAll, $pullAll & $addToSet operators in MongoDB, lets take them one by one


$push operator is an operator in MongoDB that would add a new element in the array on the right.
Say we have a document as 
{ "_id" : "1", "test" : [  1,  2,  3,  4,  5 ] }

To add a new element to the array i can simply say
> db.testarray.update({"_id":"1"},{$push:{"test":6}})

and now when i do a find on the collection 
> db.testarray.find()
{ "_id" : "1", "test" : [  1,  2,  3,  4,  5,  6 ] }


$pop unlike $push is an operand in MongoDB to remove elements from the array in a document from the right hand side.

Say we have a document as 
{ "_id" : "1", "test" : [  1,  2,  3,  4,  5, 6 ] }

To add a new element to the array i can simply say
> db.testarray.update({"_id":"1"},{$pop:{"test":1}})

and now when i do a find on the collection 
> db.testarray.find()
{ "_id" : "1", "test" : [  1,  2,  3,  4,  5] }

The value that you specify against the field in the $pop document is actually irrelevant and does not hold any significance, however a negative value for the same would pop elements from the left and side rather than right.


We learned above as to remove elements from the right or left of an array using the $pop operator, additionally MongoDB gives you a operand to remove a value from an array irrespective of its position in the array

Say we have a document as 
{ "_id" : "1", "test" : [  1,  2,  3,  4,  5 ] }

To add a more that one element to the array i can simply say
> db.testarray.update({"_id":"1"},{$pull:{"test":4}})

and now when i do a find on the collection
> db.testarray.find()
{ "_id" : "1", "test" : [  1,  2,  3,  5 ] }

In case there are multiple entries in the array with the same value , the pull operator would remove all the elements in the array matching the value being passed for $pull.


Very similar in terms of functioning as compared to $push, the $pushAll operator adds more than one element in the document

Say we have a document as 
{ "_id" : "1", "test" : [  1,  2,  3,  4,  5 ] }

To add a more that one element to the array i can simply say
> db.testarray.update({"_id":"1"},{$pushAll:{"test":[6,7,8]}})

and now when i do a find on the collection
> db.testarray.find()
{ "_id" : "1", "test" : [  1,  2,  3,  4,  5,  6,  7,  8 ] }


Very similar in terms of functioning the $pullAll operator removes more than one element in the document matching the values passed in the array while calling the $pullAll

Say we have a document as 
{ "_id" : "1", "test" : [  1,  2,  3,  4,  5 ,1] }

To remove elements with value 1 and 5 in the array i can simply say
> db.testarray.update({"_id":"1"},{$pullAll:{"test":[1,5]}})

and now when i do a find on the collection
> db.testarray.find()
{ "_id" : "1", "test" : [  2,  3,  4] }


There are situations while data modelling where you sometime want to treat the document as a unique set of elements. To support such requirements MongoDB gives you the $addToSet operator, which by definition adds  a element value in the array towards the right if it does not exist in the array, if it does , the execution of the statement with the operator would have no effect.

Say we have a document as 
{ "_id" : "1", "test" : [  1,  2,  3,  4,  5] }

To remove elements with value 6 in the array i can simply say
> db.testarray.update({"_id":"1"},{$addToSet:{"test":6}})

and now when i do a find on the collection
> db.testarray.find()
{ "_id" : "1", "test" : [  1, 2,  3,  4, 5, 6] }

In case you execute the statement again , it wont have any effect as the element 6 is already there in the array.

I guess that's all, you should by now be comfortable playing around with arrays in your document.

6 Jan 2014

Introduction to npm (NodeJS package manager) - NodeJS

Like any other programming language which has a way to create a package, NodeJS package manager most often called as npm is how dependencies can be resolved while creating a NodeJS application. You can compare it to a maven packaging that we do in a java application.

The basic file that is at the core required to create a package is package.json

Step 1 : Create a package.json 

At the application create a file called package.json, lets see a sample package.json file
  "name": "RestApp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app.js"
  "dependencies": {
    "express": "3.2.6",
    "jade": "*",
    "mongoskin": "~0.6.0"

Now in this file you can easily drive similarity with a pom.xml file that you have in maven project.

The above example shows the simplest form and a set of standard stuffs that you declare in your NodeJS application.

The first section is more of a identifier for the application where you declare the name, version, private and starting js file which is the key file to load the application. Next comes the dependencies part, NodeJS as such has numerous number of modules (can be treated as different frameworks developed and ready to be used to solve a specific problem statement) which can be imported in your NodeJS application and used. The way to do it is declaring a json field in your dependencies of your package with the name and the version of the module that you want to use. 
In this example there are three modules that has been added in the package as a dependency, we will try to cover even some of the popular modules later in this section briefly.

Step 2 : Install a package / dependencies in a NodeJS application

Now once you have created your package.json for your application lets try to understand how to install the package and what actually it does.

Lets create a home directory for my application, say i would use D:/RestApp to be my app home location

I will go to the command prompt of my application home location and execute the following command

npm install

which resulted in to the below trace on my command prompt

D:\RestApp>npm install
npm http GET https://registry.npmjs.org/express/3.2.6
npm http GET https://registry.npmjs.org/mongoskin
npm http GET https://registry.npmjs.org/jade
npm http 304 https://registry.npmjs.org/jade
npm http 304 https://registry.npmjs.org/mongoskin
npm http 304 https://registry.npmjs.org/express/3.2.6
npm http GET https://registry.npmjs.org/connect/2.7.11
npm http GET https://registry.npmjs.org/range-parser/0.0.4
npm http GET https://registry.npmjs.org/cookie/0.1.0
npm http GET https://registry.npmjs.org/fresh/0.1.0
npm http GET https://registry.npmjs.org/buffer-crc32/0.2.1
npm http GET https://registry.npmjs.org/mkdirp/0.3.4
npm http GET https://registry.npmjs.org/methods/0.0.1
npm http GET https://registry.npmjs.org/commander/0.6.1
npm http GET https://registry.npmjs.org/cookie-signature/1.0.1
npm http GET https://registry.npmjs.org/send/0.1.0
npm http GET https://registry.npmjs.org/debug
npm http GET https://registry.npmjs.org/mongodb/1.3.19
npm http GET https://registry.npmjs.org/mkdirp
npm http GET https://registry.npmjs.org/commander/2.0.0
npm http GET https://registry.npmjs.org/character-parser/1.2.0
npm http GET https://registry.npmjs.org/monocle/1.1.50
npm http GET https://registry.npmjs.org/with
npm http GET https://registry.npmjs.org/transformers/2.1.0
npm http GET https://registry.npmjs.org/constantinople
npm http 304 https://registry.npmjs.org/range-parser/0.0.4
npm http 304 https://registry.npmjs.org/connect/2.7.11
npm http 304 https://registry.npmjs.org/buffer-crc32/0.2.1
npm http 304 https://registry.npmjs.org/cookie/0.1.0
npm http 304 https://registry.npmjs.org/fresh/0.1.0
npm http 304 https://registry.npmjs.org/mkdirp/0.3.4
npm http 304 https://registry.npmjs.org/methods/0.0.1
npm http 304 https://registry.npmjs.org/commander/0.6.1
npm http 304 https://registry.npmjs.org/send/0.1.0
npm http 304 https://registry.npmjs.org/cookie-signature/1.0.1
npm http 304 https://registry.npmjs.org/debug
npm http 304 https://registry.npmjs.org/mongodb/1.3.19
npm http 304 https://registry.npmjs.org/mkdirp
npm http 304 https://registry.npmjs.org/commander/2.0.0
npm http 304 https://registry.npmjs.org/character-parser/1.2.0
npm http GET https://registry.npmjs.org/mime/1.2.6
npm http GET https://registry.npmjs.org/bson/0.2.2
npm http GET https://registry.npmjs.org/kerberos/0.0.3
npm http GET https://registry.npmjs.org/qs/0.6.5
npm http GET https://registry.npmjs.org/cookie/0.0.5
npm http GET https://registry.npmjs.org/bytes/0.2.0
npm http GET https://registry.npmjs.org/formidable/1.0.14
npm http GET https://registry.npmjs.org/send/0.1.1
npm http GET https://registry.npmjs.org/pause/0.0.1
npm http 304 https://registry.npmjs.org/monocle/1.1.50
npm http 304 https://registry.npmjs.org/with
npm http 304 https://registry.npmjs.org/transformers/2.1.0
npm http 304 https://registry.npmjs.org/constantinople
npm http GET https://registry.npmjs.org/uglify-js/2.4.0
npm http GET https://registry.npmjs.org/promise
npm http GET https://registry.npmjs.org/css
npm http GET https://registry.npmjs.org/uglify-js
npm http GET https://registry.npmjs.org/uglify-js
npm http GET https://registry.npmjs.org/readdirp
npm http 304 https://registry.npmjs.org/bson/0.2.2
npm http 304 https://registry.npmjs.org/kerberos/0.0.3
npm http 304 https://registry.npmjs.org/qs/0.6.5
npm http 304 https://registry.npmjs.org/cookie/0.0.5

> kerberos@0.0.3 install D:\RestApp\node_modules\mongoskin\node_modules\mongodb\
> (node-gyp rebuild 2> builderror.log) || (exit 0)

e "C:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin\\..\..\node_modules
\node-gyp\bin\node-gyp.js" rebuild

> bson@0.2.2 install D:\RestApp\node_modules\mongoskin\node_modules\mongodb\node
> (node-gyp rebuild 2> builderror.log) || (exit 0)

D:\RestApp\node_modules\mongoskin\node_modules\mongodb\node_modules\bson>node "C
:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin\\..\..\node_modules\nod
e-gyp\bin\node-gyp.js" rebuild
npm http 304 https://registry.npmjs.org/bytes/0.2.0
npm http 304 https://registry.npmjs.org/formidable/1.0.14
npm http 304 https://registry.npmjs.org/send/0.1.1
npm http 304 https://registry.npmjs.org/pause/0.0.1
npm http 304 https://registry.npmjs.org/mime/1.2.6
npm http GET https://registry.npmjs.org/mime
npm http 304 https://registry.npmjs.org/uglify-js/2.4.0
npm http 304 https://registry.npmjs.org/promise
npm http 304 https://registry.npmjs.org/css
npm http 304 https://registry.npmjs.org/uglify-js
npm http 304 https://registry.npmjs.org/uglify-js
npm http GET https://registry.npmjs.org/uglify-to-browserify
npm http GET https://registry.npmjs.org/optimist
npm http GET https://registry.npmjs.org/source-map
npm http GET https://registry.npmjs.org/async
npm http GET https://registry.npmjs.org/is-promise
npm http GET https://registry.npmjs.org/css-parse/1.0.4
npm http GET https://registry.npmjs.org/css-stringify/1.0.5
npm http 304 https://registry.npmjs.org/readdirp
npm http 304 https://registry.npmjs.org/mime
npm http GET https://registry.npmjs.org/minimatch
npm http 304 https://registry.npmjs.org/is-promise
npm http 304 https://registry.npmjs.org/async
npm http 304 https://registry.npmjs.org/css-parse/1.0.4
npm http 304 https://registry.npmjs.org/css-stringify/1.0.5
npm http 304 https://registry.npmjs.org/source-map
npm http 304 https://registry.npmjs.org/uglify-to-browserify
npm http 304 https://registry.npmjs.org/optimist
npm http GET https://registry.npmjs.org/wordwrap
npm http GET https://registry.npmjs.org/amdefine
npm http 304 https://registry.npmjs.org/minimatch
npm http GET https://registry.npmjs.org/lru-cache
npm http GET https://registry.npmjs.org/sigmund
npm http 304 https://registry.npmjs.org/wordwrap
npm http 304 https://registry.npmjs.org/amdefine
npm http 304 https://registry.npmjs.org/lru-cache
npm http 304 https://registry.npmjs.org/sigmund
mongoskin@0.6.1 node_modules\mongoskin
└── mongodb@1.3.19 (kerberos@0.0.3, bson@0.2.2)

express@3.2.6 node_modules\express
├── methods@0.0.1
├── fresh@0.1.0
├── cookie-signature@1.0.1
├── range-parser@0.0.4
├── debug@0.7.4
├── buffer-crc32@0.2.1
├── cookie@0.1.0
├── commander@0.6.1
├── mkdirp@0.3.4
├── send@0.1.0 (mime@1.2.6)
└── connect@2.7.11 (qs@0.6.5, pause@0.0.1, bytes@0.2.0, cookie@0.0.5, formidable
@1.0.14, send@0.1.1)

jade@1.0.2 node_modules\jade
├── character-parser@1.2.0
├── commander@2.0.0
├── mkdirp@0.3.5
├── transformers@2.1.0 (promise@2.0.0, css@1.0.8, uglify-js@2.2.5)
├── monocle@1.1.50 (readdirp@0.2.5)
├── constantinople@1.0.2 (uglify-js@2.4.8)
└── with@2.0.0 (uglify-js@2.4.0)


Now if you look at different things the npm command did, it actually took the dependencies in your package.json and imported them and any internally dependent libraries required for the modules under the node_modules folder structure in your application home directory. 

Once you have done this you can easily use the features / functionalists that is offered out of the box by the imported modules, how do we manually import it in your application is something that i would cover in my next NodeJS article.

Some popular NodeJS modules

  • Express - NodeJS modules for creating a web application
  • Jade - Jade template engine
  • mongoskin - Module to interact and communicate with MongoDB database
  • Cofee-Script - Unfancy javascript
  • Mocha - Test framework
  • Underscore - Helper library
  • Connect - High performance middle-ware framework  

3 Jan 2014

MongoDB - Basic DB operations / A CRUD Introduction

Lets come a step closer to start using and understanding mongodb. We all have been quite in a habit in understanding database via some of the very conventional databases that we have been using such as Oracle, MySQL, SQL etc. Although MongoDB is not a substitute to these relational databases (as mostly mistaken), even then lets try to drive a analogy between MongoDB and some of the conventiaonal databases we have been using.  


Sql term "database" remains the same in MongoDB as well.

Sql term/concept "table" translates to "collection" in MongoDB.

Sql term/concept "column" translates to "field" in MongoDB.

Sql term/concept "row" translates to "document / BSON document" in MongoDB.

Sql term/concept "index" remains same in MongoDB.

Sql term/concept "primary key" also remains same in MongoDB, the only difference is that in MongoDB all collection has a primary key _id which is a auto generated value in MongoDB.


Lets take now some examples along some very CRUD operations differ from how we have been doing in the conventional databases.

Note - To execute all the commands in MongoDB, simply go to the command prompt and type in command mongo at MDB_HOME location on the command prompt.

To switch to the database and or create a database, simply use the command 'use <db_name>', e.g. use nimblegeek

Figure 1: Screen shot showing switch / create database in MongoDB


Lets take an example to create a table or collection

    username Varchar(30),
    first_name Varchar(50),
    last_name Varchar(50),
    age Number,
    status char(1),
    PRIMARY KEY (id)

db.users.insert( {
    username: "anup_gaurav",
    first_name: "Anup",
    last_name: "Gaurav"
    age: 55,
    status: "A"

 } )


Lets take an example to alter data in MongoDB and see how its different from the conventional way

ALTER TABLE users ADD create_date DATETIME;

{$set:{create_date: new Date()}},

Note - The mongoDB update method has three parts, the first one is for the condition that you want to impose, the second part is to set and unset things and the last part is to signify if multiple records can be updated or not.

Lets take another example where we want to drop a field from a MongoDB document

ALTER TABLE users DROP create_date DATETIME;

{$unset:{create_date: ""}},


Lets now see an example as to how we can create indexes in a MongoDB collection.

CREATE INDEX user_name_age_index ON users (username, age DESC);


Where in the above statement 1 signifies ASC and -1 signifies DESC.


Lets now try to drive an analogy as how to insert record in SQL and MongoDB

Insert into users(username,first_name,last_name,age,status) values ('anup_gaurav','Anup','Gaurav',32,'A')



Well lets try to cater to a variety of select statements that we can think of



SQL/MangoDB Select Query with where clause 


SQL/MangoDB Select Query with where clause having greater than operator
SELECT username,first_name,last_name from users WHERE age > 20;


SQL/MangoDB query with not equal to and AND operator
SELECT * FROM USERS WHERE age != 20 AND status='A';


SQL/MangoDB query with less that equal to and AND operator
SELECT * FROM USERS WHERE age > 20 AND age <= 60;


SQL/MangoDB Select query with OR operator
SELECT * FROM USERS WHERE age > 20 OR status = 'A';


SQL/MangoDB Select query with LIKE operator
SELECT * FROM USERS WHERE first_name like '%Ag%';


SELECT * FROM USERS WHERE first_name like 'Ag%';


SQL/MangoDB Select query with ORDER_BY operator


We use 1 for ASC and -1 for DESC while sorting the result in a MongoDB query.

SQL/MangoDB Select query with COUNT operator


SELECT count(username) FROM USERS;


SQL/MangoDB Select query with DISTINCT operator


SQL/MangoDB Select query with LIMIT operator

db.users.findOne(); or db.users.find().limit(1);


UPDATE USERS SET status='I' where age => 58;





I guess that enough for you now to get started and doing DB. 

Powered by Blogger.


© 2013 NimbleGeek. All rights resevered. Designed by Templateism

Back To Top