MongoDB + Java + Maven Sample Application


Prerequisite: Download and Install MongoDB (http://docs.mongodb.org/manual/installation/) on your local machine and run two instances in two separate terminal/command prompt. This sample app is developed on Mac OS/Linux env.

1. Start MongoDB server using : ./mongod

2. Start MongoDB client : ./mongo

Add MongoDB Jar dependency in your project:

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

 

Sample MONGODB CRUD code:

package com.db;
import java.util.List;
import java.util.Set;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;

public class MongoConnectionManager {
	static DBCursor cursor;

	public static void main(String[] args) {

	try{
		System.out.println("Connecting with MongoDB......");
		//DB connection after ver 2.10.0
		MongoClient mongoconn = new MongoClient("localhost",27017 );
		//Get database
		DB db = mongoconn.getDB( "test" );
		System.out.println("Database Name: "+db.getName());

		//Display all databases
		List<String> dbs = mongoconn.getDatabaseNames();
		for(String mydb : dbs){
			System.out.println(mydb);
		}

		//If MongoDB is installed on Secure mode
		//boolean auth = db.authenticate("username", "password".toCharArray());

		//Get Collection/tables names
		Set<String> colls = db.getCollectionNames();

		for (String s : colls) {
		    System.out.println(s);
		}

		//Get Collection

		DBCollection coll = db.getCollection("mynames");
		coll.createIndex(new BasicDBObject("email", 1));  // create index on "i", ascending

		System.out.printf("Collection Names:"+db.getCollectionNames());

		//Drop collections
		coll.drop(); 

		//Insert new records/documents
		BasicDBObject doc1 = new BasicDBObject();

		//Insert values into document/record
        doc1.put("name", "Rajiv");
        doc1.put("email", "rajivmca2004@yahoo.com");
        doc1.put("count",1);

     // Insert values in Collection
        coll.insert(doc1);

        BasicDBObject doc2 = new BasicDBObject();

		//Insert values into document/record
        doc2.put("name", "Mohit");
        doc2.put("email", "mohit@yahoo.com");
        doc2.put("count",2);

       // Insert values in Collection
        coll.insert(doc2);

        //Fecth only first doc

        DBObject mydoc= coll.findOne();
        System.out.println("Only First Doc :"+mydoc);

        //Insert and fetch Multiple doc

        for (int i = 0; i < 10; i++) {
			coll.insert(new BasicDBObject().append("count", i));
		}

        //Total documents
       cursor= coll.find();

        while(cursor.hasNext()){
        	System.out.println(cursor.next());
        }

        //Getting A Single Document with A Query
        BasicDBObject query= new BasicDBObject();
        query.put("name","Rajiv");
        cursor= coll.find(query);
        System.out.print("Getting A Single Document with A Query: \n");

        //Iterate over database results
        while(cursor.hasNext()){
        	System.out.println(cursor.next());
        }

        //Conditional Queries, documents where i > 50. We could also get a range, say 20 < i <= 30 :
        query = new BasicDBObject();
        query.put("count", new BasicDBObject("$gt", 1).append("$lte", 30));  // i.e.   20 < i <= 30

        cursor = coll.find(query);

        while(cursor.hasNext()) {
            System.out.println("Comparison =>"+cursor.next());
        }
        System.out.println("Total documents: "+coll.getCount());

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

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