JBoss application server tutorials

  • Full Screen
  • Wide Screen
  • Narrow Screen
  • Increase font size
  • Default font size
  • Decrease font size

MongoDB tutorial for Java EE developers

 

mongodb tutorial example javaThis tutorial provides a short introduction to MongoDB no-sql database and shows how to interact with it
from a Java application server (JBoss AS).

 

 

 

 

MongoDB (which stands for "humongous") is an open source, high-performance, schema-free, document-oriented database written in the C++ programming language. The database is document-oriented so it manages collections of JSON-like documents.

The easiest (and recommended) way to install MongoDB is to use the pre-built binaries

Download binaries here

Once you're done, unzip the downloaded binary package to the location of your choice.Then, download the jar driver which is hosted at github.

Download the jar driver here

Copy the file under your JBoss library folder (Ex. C:\jboss-6.0.0.Final\common\lib )

By default MongoDB will store data in \data\db, but it won't automatically create that folder, so we do so here:

C:\> mkdir \data
C:\> mkdir \data\db


Ok. We're done with set-up. Now move to the "bin" folder of mongodb

mongodb tutorial java

The important binaries for a first run are:

mongod.exe - the database server
mongo.exe - the administrative shell

To start the database, click mongod.exe in Explorer

mongodb example tutorial
Data can be inserted directly using the mongo.exe shell or via the Java Mongo db driver.

For this purpose we will create a simple Servlet which will run on JBoss AS 6 and insert some data. The Servlet will insert a Collection containing a DB Object into MongoDB. This is our sample DBObject we're going to insert:

mongodb example tutorial java

public class MongoServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    Mongo m = null;   


    public MongoServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    public void init(ServletConfig config)
    {
        try {
            m = new Mongo( "localhost" );
            System.out.println("Connected");
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MongoException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();

        DB db = m.getDB( "test" );

        out.println("Got db");

        BasicDBObject doc = new BasicDBObject();

        doc.put("name", "Michael");
        doc.put("surname", "Owen");
        doc.put("age", 31);

        DBCollection coll = db.createCollection("player", doc);

        BasicDBObject career = new BasicDBObject();

        career.put("goals", 100);
        career.put("matches", 200);

        doc.put("career", career);

        coll.insert(doc);
        coll.insert(career);

        out.println("Inserted DBObject "+coll);

    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

}

Note: The Mongo object instance actually represents a pool of connections to the database; you will only need one object of class Mongo even with multiple threads.

To make a connection to a MongoDB, you need to have at the minimum, the name of a database to connect to.

DB db = m.getDB( "test" );

The database doesn't have to exist - if it doesn't, MongoDB will create it for you. Once recalled the Servlet it should output:

Got db
Inserted DBObject player
Now let's try to query for this collection on the mongo console:

E:\mongodb-win32-i386-1.8.1\bin>mongo
MongoDB shell version: 1.8.1

connecting to: test
> db.player.find()
{ "_id" : ObjectId("4dd28ad9b71d9d0a37845251"), "name" : "Michael", "surname" :
"Owen", "age" : 31, "career" : { "goals" : 100, "matches" : 200 } }
{ "_id" : ObjectId("4dd28ad9b71d9d0a37845252"), "goals" : 100, "matches" : 200 }



If you want to query Collections from Java you can iterate on the collection names:
Set<String> colls = db.getCollectionNames();

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

To get a collection to use, just specify the name of the collection to the getCollection(String collectionName) method:
DBCollection coll = db.getCollection("player")

For more information refer to the official documentation:

http://www.mongodb.org/display/DOCS/Home
http://www.mongodb.org/display/DOCS/Java+Tutorial#JavaTutorial-InsertingaDocument<

MongoDB tutorial for Java EE developers
Francesco Google+
Top Programming Sites
You are here Home