Manipulating MongoDB with Java
Initially, i was thinking of writing about why i was using MongoDB and how it was different from other databases. However, you can easily find all of these information on the internet.
To sum up, MongoDB (from “humongous”) is a scalable, high-performance, open source NoSQL database. It is a document-oriented database. This means, data will be stored in the form of documents. Documents are stored within Collections (Table, if you would like to make a reference to a ‘normal’ database). Graphically, here is how data is stored.
Getting started with MongoDB on Windows.
- First, you will need to download MongoDB for Windows, either 32-bit or 64-bit depending on your respective operating system. You can download the files here.
- Create a folder in your root folder and name it ‘data’. Create a subfolder within data and name it db. By default, MongoDB will store data there but you can change that by using mongod –dbpath.
- Extract your downloaded file. Copy it to your root folder. (For e.g C:\Mongo)
- Open mongod.exe from a CMD window.
- Open mongo.exe from another CMD window.
You can find a more comprehensive guide for Windows,UNIX or Mac OSX here.
Java & MongoDB.
I personally use Eclipse IDE to code in Java. However, adding drivers should be possible with any other IDE You should add the MongoDB drivers to your new project, under the ‘libraries’ tab. Click on External JARS and browse to the location of the driver. You can download the Java Driver here (Latest version is 2.7.3) and any other drivers can be found on MongoDB’s GitHub.
After you are done with all these,start coding. (I am assuming that MongoDB is already running on your computer)
Import the following. These are self-explanatory.
import java.net.*; import com.mongodb.*;
Mongo dpkg = new Mongo();
DB db = dpkg.getDB( "dpkg" );
DBCollection coll = db.getCollection("test") ;
Here a new instance of MongoDB is created, called dpkg. We are also choosing the database dpkg. Make sure the database exists. If it does not exist, MongoDB will not create it for you. Finally we are getting the Collection test and assigning it to a variable coll. If test does not exist, it will be automatically created.
Adding documents:
// Adding a document to the Collection "test"
BasicDBObject data = new BasicDBObject();
data.put("X", 1);
data.put("Y", 2);
coll.insert(data);
The above code adds the data {X : 1} and {Y : 2} in a document to the collection test. Here is a screenshot of the document in the collection.
Displaying all documents in a collection:
//Displaying all the documents in the Collection "test"
DBCursor curs = coll.find();
while(curs.hasNext()) {
DBObject a = curs.next();
System.out.println(a);
}
The above code will print all the documents in the Collection test.
Searching for a particular document:
Additionally, you can specify criteria and retrieve documents matching those criteria only. To do that, let us add a new document within our collection test.
BasicDBObject data1 = new BasicDBObject();
data1.put("X", 3);
data1.put("Y", 2);
coll.insert(data1);
X now has a value of 3 in this document. To retrieve the document(s) where X = 3 , do the following.
BasicDBObject query = new BasicDBObject("X", 3);
DBCursor curs1 = coll.find(query);
while(curs1.hasNext()) {
DBObject b = curs1.next();
System.out.println(b);
}
This will retrieve the document where the criteria are matched. The screenshot shows this.
You can also specify which fields you want to display.
BasicDBObject query1 = new BasicDBObject("X", 3);
BasicDBObject fields = new BasicDBObject("X",true).append("_id",false) ;
DBCursor curs2 = coll.find(query1,fields);
while(curs2.hasNext()) {
DBObject c = curs2.next();
System.out.println(c);
}
query1 is the condition. All documents where X = 3 will be displayed. fields is the field that you want to display. In this case, we want to display X only. You MUST explicitly declare “_id” to false to remove the fields “_id” and “$oid” from the document. The output is shown below.
You can also retrieve only the value associated with X. To illustrate this example, consider the following database.
If i want to retrieve the first record, i.e, Mozammil, my code would look like this.
BasicDBObject query = new BasicDBObject("StudentID", "1010101" );
DBCursor curs = coll.find(query);
while(curs.hasNext()) {
DBObject o = curs.next();
System.out.println(o.get("Firstname"));
}
Notice the o.get(“Firstname”). This will only print Mozammil to the console.
Deleting documents:
To delete a document, you can simply use, collection.remove(query).
coll.remove(new BasicDBObject());
The above code will delete everything in the collection test. No query means it will delete all documents.
You can also specify criteria to delete particular documents. For e.g, if you want to delete all documents where X = 3. You can do this.
BasicDBObject query2 = new BasicDBObject("X", 3);
DBCursor curs3 = coll.find(query);
while(curs3.hasNext()) {
DBObject b = curs3.next();
coll.remove(b) ;
}
Eventually, all documents where X =3 will be removed.
Finally, make sure you use try & catch to cater for any errors that might occur during manipulating the database. Here is the full code.
import java.net.*;
import com.mongodb.*;
public class MongoManip {
public static void main(String[] args) {
try {
Mongo dpkg = new Mongo();
DB db = dpkg.getDB( "dpkg" );
DBCollection coll = db.getCollection("test") ;
// Adding data to the Collection "test"
BasicDBObject data = new BasicDBObject();
data.put("X", 1);
data.put("Y", 2);
coll.insert(data);
BasicDBObject data1 = new BasicDBObject();
data1.put("X", 3);
data1.put("Y", 2);
coll.insert(data1);
//Displaying all the documents in the Collection "test"
DBCursor curs = coll.find();
while(curs.hasNext()) {
DBObject a = curs.next();
System.out.println(a);
}
//Displaying documents based on a certain condition (Searching)
BasicDBObject query = new BasicDBObject("X", 3);
DBCursor curs1 = coll.find(query);
while(curs1.hasNext()) {
DBObject b = curs1.next();
System.out.println(b);
}
//Displaying documents (& specific fields) based on a certain condition
BasicDBObject query1 = new BasicDBObject("X", 3);
BasicDBObject fields = new BasicDBObject("X",true).append("_id",false) ;
DBCursor curs2 = coll.find(query1,fields);
while(curs2.hasNext()) {
DBObject c = curs2.next();
System.out.println(c);
}
//Deleting every documents in the Collection "test"
coll.remove(new BasicDBObject());
//Deleting documents based on a certain condition.
BasicDBObject query2 = new BasicDBObject("X", 3);
DBCursor curs3 = coll.find(query);
while(curs3.hasNext()) {
DBObject b = curs3.next();
coll.remove(b) ;
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
}
}
This is only a beginner tutorial to show the basic manipulations of MongoDB with Java. In my next blog post, i will focus more on Advanced Querying with MongoDB.
Stay tuned.
Unofficial guide for UOM’s WI-FI.
Here is a good news and a bad news.
Finally the University Of Mauritius’ administration has implemented WI-FI in the campus.Bad news, you need to be a little IT-proficient to get it to work on your device. While the network admins have been kind enough to provide us with a windows guide to connecting with the network, most Linux and mobile users have been experiencing issues to do same.
Here is a little guide to help you connect to the network. I cannot guarantee it will work on your device. Your device should be compatible with the authentication protocol that is being used: PEAPv0 with EAP-MSCHAPv2, but according to this, most recent hardware should be compatible.
Prerequisites:
1) You will need to accept the Terms and Conditions for WI-FI before being able to connect. Carrotmadman6 explains this procedure in detail in his blog.
2) You will use the same login information to connect to the WI-FI network as the student portal.
3) If you want to connect using Ubuntu or any other Linux distributions, you will need a Windows laptop first to download the certificate.
Connecting with Ubuntu 11.04
After a number of persistent trials, i got it to work on my Ubuntu 11.04. Here is what i did.
1) Connect to wifiprovisioning. If it asks you for a security key, use uomwifi01. Open up your browser.Navigate to any URL (For e.g. Google.com), a login dialog box should appear prompting for a username and password. Your username is: uomwifi\YourID (for e.g. uomwifi\101010) and your password is the same one you use for the student portal. Please note the uomwifi\ in front of your username.
2) When you have already connected to the network, you will need to download the CA certificate which is a .cer file.Click on Download a CA Certificate, certificate chain, or CRL as shown in the image below.
3) Click on Download CA Certificate in the next page as shown below.
4) It should prompt you to download a .cer file as shown below. Save it, you will use this later on your linux distribution to connect to the network.
5) Switch to your linux distribution.Open up Network Manager and add a new wireless connection. Use a meaningful connection name and under the wireless tab, use the following details.
Note that we are now connecting to uomstudent directly.
6) Under the wireless security tab, use the following configurations.
Security: WPA & WPA2 Enterprise.
Authentication: Protected EAP (PEAP).
CA certificate: Browse for the .cer file you downloaded & saved
Username: Your id. (For e.g, 101010) Note that we are no longer prefixing it with uomwifi\
Password: Your password
6) Click on save, and connect to uomstudent. Pray a little. With some luck, it should work.
I have also tried connecting with an iPhone 2G, iPhone 3GS, iPad2 and a Kindle. I have successfully connected to the network with all the apple devices. No luck with the kindle and according to Amazon support, the kindle does not support this authentication method.
Here is how i connected with the iPhone 2G.
1) I connected to wifiprovisioning with the security key: uomwifi01. Basically, you will follow the same steps as i did in windows 7.
2) It will prompt you to enter your login information for the cert server. Use uomwifi\your id and the same password again to login. Click on Download CA Certificate, Certificate Chain or CRL. On the next page, click on Download CA certificate. You will be prompted to install the certificate. Install the certificate as follows.
3) Disconnect from wifiprovisioning and connect to uomstudent. Username should be your id (without uomwifi\) and password is your student portal’s password.
4) You will be prompted to accept and install a certificate. Do it and you should be able to use the internet.
Follow the same steps on an iPad or any other apple devices and you should be able to connect successfully. As a side note, if anybody is willing to lend me a Nokia phone for a few minutes, i will try to connect with it.
UPDATE 1 :
Today, i got a Samsung Galaxy Tab GT-P1000 to test UOM’s WI-FI. It was running Android 2.2 (froyo). Courtesy of my friend, Zuleikha. (Thanks again)
(Sorry for low quality – Taken with an iPhone)
I did struggle with it a bit, given that i am not so familiar with Android but it should be easy to configure for any other Android users.
Here is what i did. First i had to get hold of the certificate. Connecting to wifiprovisioning and acquire the certificate did not help at all. I get a 401 – Not authorised error. Apparently the browser has been sending incorrect headers. So i managed to get a previously-downloaded certificate from a windows 7 laptop and install it.
How to install the certificate?
- Go to Settings, Location and Security and under Credential Storage, click on Set Password.
- After you have done that, check the Use secure credentials checkbox.
- To install the certificate, you will need to copy the certificate to your external sd card’s root folder. However, copying the certificate (.cer) did not work for me. I have had to rename it to .crt for it to work. Apparently, android does not recognise .cer as a valid BASE-64 certificate.After you have copied the certificate, click on Install encrypted certificates from SD card.
- Alternatively, you can just browse to this link on your browser to install this certificate. I downloaded it with a Windows 7 laptop and it should work fine. (http://dpkg.me/certnew.crt)
Having done that, ti is time to configure your WI-FI settings.
- Go to WI-FI settings.
- Add a WI-FI network.
- Use the following configurations, as it is.
- Under Identity, use your student id. (For e.g. 1010101)
- Leave Anonymous Identity blank.
- Password is the same password you are using to access the student’s portal (online.uom.ac.mu).
UPDATE 2 :
The Kindle 3rd edition does not support UOM’s WI-FI protocol. It is the same for any other Kindle.
I will update this post if i am able to connect with any other devices.
Stay tuned.
Object-Oriented Programming (OOP) with Python

Image source: http://www.codercaste.com
From personal experience, shifting from procedural programming (linear programming) to object-oriented programming was quite difficult for me. They are two very different concepts: Procedural executes code from top to bottom in an orderly manner while Object-oriented programming is concerned with objects and classes which can be reused anywhere in the program without defining them in order. One major advantage of OOP is code reusability.
If you are just starting out, chances are you have been programming in a procedural manner which is also known as linear programming. While you can follow or write codes in a linear way in object oriented, it doesn’t really matter.
This tutorial is language-specific to python because it is an easy programming language and even if you haven’t had any programming experience beforehand, you can easily start out with Python.
Before I take some real world examples, here are some terminologies you will need to get acquainted with. (Source: Link)
- A class is a set of functions that work together to accomplish a task. It can contain or manipulate data, but it usually does so according to a pattern rather than a specific implementation. An instance of a class is considered an object.
- An object receives all of the characteristics of a class, including all of its default data and any actions that can be performed by its functions. The object is for use with specific data or to accomplish particular tasks. To make a distinction between classes and objects, it might help to think of a class as the ability to do something and the object as the execution of that ability in a distinct setting.
- A method simply refers to a function that is encased in a class.
Without further delay, let’s move on with some real world examples.
A class can be ‘Animal’ and an object can be ‘dog’. Similarly a class can be ‘Human’ and an object can be ‘Man’ or a second object can be ‘Woman’. Additionally, ‘John’ can be an object of the class ‘Man’. The object will inherit the characteristics of their parent class.
Let us take a parent class ‘Man’ and an object ‘John’. If we define the characteristics of ‘Man’ as having a name, age and a contact number, ‘John’ should have all these characteristics. Moreover if we define the behaviors (also known as methods) of the class ‘Man’ to be eating, sleeping and reading, ‘John’ should inherit these behaviors too.
The following code further explains it.
class Animals():
def __init__(self,name,age):
self.name=name
self.age=age
def sound(self,sound):
print sound
def display(self):
print self.name,self.age
dog=Animals('woofy',3)
dog.sound('barks')
dog.display()
We are defining our new parent class Animals with attributes/fields name, age and methods sound, display.
class Animals(): def __init__(self,name,age): self.name=name self.age=age
This is a constructor method. It is used to initialise the fields associated with the objects. In this case, name and age.
def sound(self,sound): print sound
This is a method/function that is part of the characteristics of the class Animals. For e.g an Animal in addition of having a name, age they can also behave in certain ways, i.e., they make a certain sound, sleep, eat. This can be further implemented in OOP. The above method will display the sound that the object makes based on the value inputted by the user.
def display(self): print self.name,self.age
This method will display the name and age of the object. Nothing difficult here.
dog=Animals('woofy',3)
dog.sound('barks')
dog.display()
Here we are :
1) Initialising the class Animals with object name dog with values woofy as name and 3 as age
2) We are also defining the sound that it makes, i.e, barks
3) Finally, we are displaying the name and age of the dog.
This is a basic introductory tutorial of object-oriented. Our next tutorial will be on inheritance which is a major topic in Object-oriented programming.
Stay tuned.
REFERENCES:
1. Download Python here.
EDITS:
1. InF suggested to change the definition of the constructor method which i totally agree with him.
Hi! My name is Mozammil Khodabacchas
I am a Computer Science student at the University Of Mauritius. In my free time (if any) i like to code, tweet and blog. I also like to take pictures spontaneously. I love soccer, my favorite team being Liverpool FC. I actively participate on Twitter , Facebook and Flickr.


















