Blog

Sign up for email updates

sbartichi's picture
Mongo Installation – CRUD operations in Mongo and SQL, a comparison
By Stefan, in Innovation, R&D Insights

May. 24th 2011 0 comments

This article is the first in a 3 part series of articles which will serve as an introduction to MongoDB as well as in setting up a MongoDB instance and running a few simple operations against it. In the second article we will talk about setting up a cluster of Mongdb master and slaves. A third article will discuss data sharding and consistency parameter tuning. This article assumes that you have core knowledge about operating systems, browser navigation, and Java.

High level description of Mongo

MongoDB is a non relational document oriented database which supports the storage of very large amounts of data through its powerful replication and autosharding capabilities.

Document Database

MongoDB is a document oriented database. Some terms are different from a standard RDBMS but have analogous to several core concepts in the RDBMS world. So a database in MongoDB means the same thing as in standard RDBMS notation, a collection is like a table in standard RDBMS notation but the difference is that it has no schema, and a document is the same as a row in a RDBMS but it is limited to only 4mb.

BSON

MongoDB stores data in a format called BSON which stands for binary JSON. Below you can see how a JSON (left) is represented as BSON (right).

More information about BSON can be found visiting http://bsonspec.org/#/specification

 

Installation

We have used windows 7 on a 64 bits Intel architecture for our examples.

Just download it from here: http://www.mongodb.org/downloads. Unzip it.
Make a directory in your root drive directory called data. So for example if you have windows create a folder in C:\ called data. The result should be C:\data.

Queries in MongoDB

I'll take you now through some examples of Create, Read, Update, Delete in Mongo.The examples will be written in mongo shell then we will present an equivalent in java.
First start the server:

mongod.exe --rest --port 27017 --dbpath /data

In order to see if the server is running you can check the status here by opening this URL in a browser: http://localhost:28017/

From now on in order to run some queries you have two options. One is to open the mongo shell and write some queries, the other is to do it programatically. First I will show you the Mongo operations for Create, Update, Delete (CRUD) and the corresponding SQL calls.

First run mongo shell where you can enter SQL like commands:

mongo.exe

In the example that follows I'll use a Car record as our data model.

SQL CRUD vs MongoDB CRUD

Create

Creating a Car element in RDBMS has the following syntax:

INSERT INTO cars(make, model)
VALUES (ìAudiî, ìA6î)

Creating a Car in Mongo shell:

car = { make: "Audi" , model: "A6"};
db.cars.save(car);
Read

In order to read all Car elements, in any RDBMS we use:

SELECT * FROM cars

The equivalent in Mongo:

db.cars.find();

If you want to filter out result in an RDBMS you use the WHERE clause:

SELECT * FROM cars WHERE make == Audi'

Which in Mongo is equivalent to:

db.cars.find({ make: "Audi" });
Update

In order to set a new property of an existing object in any RDBMS you type:

UPDATE cars SET model = ìA7î WHERE make == ìAUDIî

In Mongo the same can be accomplished with:

db.cars.update({ model: "A7"}, {make: "Audi", model: "A7"});

Keep in mind that in MongoDB you don't have schema attached to collections so adding/removing attributes when doing an update is perfectly valid:

db.cars.update({ model: "A7"}, {make: "Audi", model: "A7", color:'red'});

Note how the second document has an additional color attribute.

Delete

The query for doing a delete a car in any RDBMS is:

DELETE FROM cars WHERE model == ìA7î

In MongoDB the equivalent is:

db.cars.remove({model:îA7î});

 

Building a simple CRUD application in java

Having compared Mongo and SQL calls for CRUD, we will now write a simple java application that performs CRUD operations with Mongo. We'll use maven in order to build it.

The following dependency is needed when you want to use MongoDB:

 <dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.4</version>
</dependency>

Now let's go into configuring the connection in a file called db.properties (it'll be located under resources directory of your maven structure):

db.replicaset.host=localhost
db.replicaset.port=27017
cars.db.name=carsdb

where db.replicaset.host and db.replicaset.port represent the host where the MongoDB server is running.

 

I will create one helper class as listed below:

public class DbFactoryBean implements FactoryBean { 
private Mongo mongo;
private String name;

@Override
public DB getObject() throws Exception {
return mongo.getDB(name);
}

@Override
public Class getObjectType() {
return DB.class;
}

@Override
public boolean isSingleton() {
return true;
}

@Required
public void setMongo(Mongo mongo) {
this.mongo = mongo;
}

@Required
public void setName(String name) {
this.name = name;
}
}

Then I created this spring configuration file:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:property-placeholder
location="classpath:db.properties"/>
<bean id="mongo" class="com.mongodb.Mongo">
<constructor-arg value="${db.replicaset.host}"/>
<constructor-arg value="${db.replicaset.port}"/>
</bean>
<bean id="db"
class="com.mongodb.spring.config.DbFactoryBean">
<property name="mongo" ref="mongo"/>
<property name="name" value="${cars.db.name}"/>
</bean>
</beans>

Now we'll create a service that will be responsible for all CRUD operations. Let's call it CarService. The db bean will be injected in it as all db operations will go through that bean. In configuration file add the following bean definition:

 <bean id="carService" class="com.tpg.impl.CarServiceImpl">
<property name="db" ref="db"/>
</bean>

Now let's go implement this service. In the following I'll show some examples of MongoDB CRUD operations written in Java.

Create

In this example I'll show how to insert a specific car by it's make.

public void insert(String make, String model) {
/** Gets the cars collection from db */
DBCollection collection = db.getCollection("cars");

/**
Build the car document.
Equivalent to car = { make: "Audi" , model: "A6"};
*/
BasicDBObject doc = new BasicDBObject();
doc.put("make", make);
doc.put("model", model);

/**
Inserts the document into the collection.
In case collection doesn't exist one will be created.
Equivalent to: db.cars.save(car);
*/
collection.insert(doc);
}
Read

In this example I'll show how to get a specific car by it's make.

public BasicDBObject get(String make) {
/** Gets the cars collection from db */
DBCollection collection = db.getCollection("cars");

/**
Build the filtered query based on model
Equivalent to : SELECT * FROM cars WHERE make == 'Audi'
*/
BasicDBObject query = new BasicDBObject();
query.put("make", make);

DBCursor cur = collection.find(query);
while(cur.hasNext()) {
BasicDBObject dbObject = (BasicDBObject) cur.next();
return dbObject;
}

return null;
}
Update

In this example I'll show how to update a model of a specific make.

public void update(String make, String model) {
/** Gets the cars collection from db */
DBCollection collection = db.getCollection(ìcars");

BasicDBObject filter = new BasicDBObject();
filter.put("make", make);

/** build the object we want to update to */
DBObject updatedCar = collection.findOne(query);
updatedCar .put("makeî, make);
updatedCar .put("modelî, model);

/** perform the update */
collection.update(filter, updatedCar);
}
Delete

In this example I'll show how to delete a car having a specific model.

public void delete(String model) {
DBCollection collection = db.getCollection("cars");
BasicDBObject filter = new BasicDBObject();
filter.put("model", model);

/** remove all the cars that have the specified model */
collection.remove(filter);
}

Now that we have all the basic scaffolding setup we can proceed in the following article to discuss about setting up a cluster of Mongdb master and slaves in order to achieve replication.

Leave a comment

News

Recognition Based on Outstanding Corporate Growth and Market LeadershipFairfax, VA – January...
Fairfax, VA (PRWeb) January 10, 2012 – Three Pillar Global, a trusted, high-growth software...
Fairfax, VA (PRWeb) January 3, 2012 – Three Pillar Global, a trusted, high-growth software...

Careers

Passionate, talented, ambitious, creative … sound familiar?

Three Pillar Global is hiring the best and brightest, and we might just be looking for you.

Check out our open positions.

Join Us