Java Tutorial

Introduction

This page is a brief overview of working with the MongoDB Java Driver.

For more information about the Java API, please refer to the online API Documentation for Java Driver

A Quick Tour

Using the Java driver is very simple. First, be sure to include the driver jar mongo.jar in your classpath. The following code snippets come from the examples/QuickTour.java example code found in the driver.

Making A Connection

To make a connection to a MongoDB, you need to have at the minimum, the name of a database to connect to. The database doesn't have to exist - if it doesn't, MongoDB will create it for you.

Additionally, you can specify the server address and port when connecting. The following example shows three ways to connect to the database mydb on the local machine :

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

Mongo m = new Mongo();
Mongo m = new Mongo( "localhost" );
Mongo m = new Mongo( "localhost" , 27017 );

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

At this point, the db object will be a connection to a MongoDB server for the specified database. With it, you can do further operations.

Authentication (Optional)

MongoDB can be run in a secure mode where access to databases is controlled through name and password authentication. When run in this mode, any client application must provide a name and password before doing any operations. In the Java driver, you simply do the following with the connected mongo object :

boolean auth = db.authenticate(myUserName, myPassword);

If the name and password are valid for the database, auth will be true. Otherwise, it will be false. You should look at the MongoDB log for further information if available.

Getting A List Of Collections

Each database has zero or more collections. You can retrieve a list of them from the db (and print out any that are there) :

        Set<String> colls = db.getCollectionNames();

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

and assuming that there are two collections, name and address, in the database, you would see

name
address

as the output.

Getting A Collection

To get a collection to use, just specify the name of the collection to the getCollection(String collectionName) method:

        DBCollection coll = db.getCollection("testCollection");

Once you have this collection object, you can now do things like insert data, query for data, etc

Inserting a Document

Once you have the collection object, you can insert documents into the collection. For example, lets make a little document that in JSON would be represented as

{
   "name" : "MongoDB",
   "type" : "database",
   "count" : 1,
   "info" : {
               x : 203,
               y : 102
             }
}

Notice that the above has an "inner" document embedded within it. To do this, we can use the BasicDBObject class to create the document (including the inner document), and then just simply insert it into the collection using the insert() method.

        BasicDBObject doc = new BasicDBObject();

        doc.put("name", "MongoDB");
        doc.put("type", "database");
        doc.put("count", 1);

        BasicDBObject info = new BasicDBObject();

        info.put("x", 203);
        info.put("y", 102);

        doc.put("info", info);

        coll.insert(doc);
Finding the First Document In A Collection using findOne()

To show that the document we inserted in the previous step is there, we can do a simple findOne() operation to get the first document in the collection. This method returns a single document (rather than the DBCursor that the find() operation returns), and it's useful for things where there only is one document, or you are only interested in the first. You don't have to deal with the cursor.

        DBObject myDoc = coll.findOne();

        System.out.println(myDoc);

and you should see

{ "_id" : "49902cde5162504500b45c2c" , "name" : "MongoDB" , "type" : "database" , "count" : 1 , "info" : { "x" : 203 , "y" : 102} , "_ns" : "testCollection"}

Note the _id and _ns elements have been added automatically by MongoDB to your document. Remember, MongoDB reserves element names that start with _ for internal use.

Adding Multiple Documents

In order to do more interesting things with queries, let's add multiple simple documents to the collection. These documents will just be

{
   "i" : value
}

and we can do this fairly efficiently in a loop

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

Notice that we can insert documents of different "shapes" into the same collection. This aspect is what we mean when we say that MongoDB is "schema-free"

Counting Documents in A Collection

Now that we've inserted 101 documents (the 100 we did in the loop, plus the first one), we can check to see if we have them all using the getCount() method.

        System.out.println(coll.getCount());

and it should print 101.

Using a Cursor to Get All the Documents

In order to get all the documents in the collection, we will use the find() method. The find() method returns a DBCursor object which allows us to iterate over the set of documents that matched our query. So to query all of the documents and print them out :

        DBCursor cur = coll.find();

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

and that should print all 101 documents in the collection.

Getting A Single Document with A Query

We can create a query to pass to the find() method to get a subset of the documents in our collection. For example, if we wanted to find the document for which the value of the "i" field is 71, we would do the following ;

        BasicDBObject query = new BasicDBObject();

        query.put("i", 71);

        cur = coll.find(query);

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

and it should just print just one document

{ "_id" : "49903677516250c1008d624e" , "i" : 71 , "_ns" : "testCollection"}
Getting A Set of Documents With a Query

We can use the query to get a set of documents from our collection. For example, if we wanted to get all documents where "i" > 50, we could write :

        query = new BasicDBObject();

        query.put("i", new BasicDBObject("$gt", 50));  // e.g. find all where i > 50

        cur = coll.find(query);

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

which should print the documents where i > 50. We could also get a range, say 20 < i <= 30 :

        query = new BasicDBObject();

        query.put("i", new BasicDBObject("$gt", 20).append("$lte", 30));  // i.e.   20 < i <= 30

        cur = coll.find(query);

        while(cur.hasNext()) {
            System.out.println(cur.next());
        }
Creating An Index

MongoDB supports indexes, and they are very easy to add on a collection. To create an index, you just specify the field that should be indexed, and specify if you want the index to be ascending (1) or descending (-1). The following creates an ascending index on the "i" field :

        coll.createIndex(new BasicDBObject("i", 1));  // create index on "i", ascending
Getting a List of Indexes on a Collection

You can get a list of the indexes on a collection :

        List<DBObject> list = coll.getIndexInfo();

        for (DBObject o : list) {
            System.out.println(o);
        }

and you should see something like

{ "name" : "i_1" , "ns" : "mydb.testCollection" , "key" : { "i" : 1} , "_ns" : "system.indexes"}

Quick Tour of the Administrative Functions

Getting A List of Databases

You can get a list of the available databases:

        Mongo m = new Mongo();

        for (String s : m.getDatabaseNames()) {
            System.out.println(s);
        }
Dropping A Database

You can drop a database by name using the Mongo object:

m.dropDatabase("my_new_db");

Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.

Comments (17)

IF YOU HAVE A QUESTION, POST IT TO THE USER GROUP.

These pages are fine for comments, but for questions, your best bet will always be the MongoDB User Group.

 
  1. Nov 01

    Anonymous says:

    Class com.mongodb.MongoAdmin not any more exists.

    Class com.mongodb.MongoAdmin not any more exists.

    1. Nov 02

      Eliot Horowitz says:

      Thanks, fixed.

      Thanks, fixed.

  2. Nov 06

    Anonymous says:

    if I have array of custom ids int myIds[]= new int[]{1,3,5}; how I can get ...

    if I have array of custom ids

    int myIds[]= new int[]{1,3,5};
    

    how I can get 3 objects from collection in one request ?

    I see $in function, but I can't make it work :(

    help pleace :)

    1. Nov 06

      Kristina Chodorow says:

      Use $in, so it's something like: BasicDBObject in = new BasicDBObject("$in", m...

      Use $in, so it's something like:

      BasicDBObject in = new BasicDBObject("$in", myIds);
      BasicDBObject query = new BasicDBObject("_id", in);
      
      collection.find(query);
      

      In JSON:

       db.collection.find({_id : {$in : [1,3,5]}})
      
      1. Nov 08

        Anonymous says:

        it work :) first time I try make in list using by BasicDBList and it's fail

        it work :)

        first time I try make in list using by BasicDBList and it's fail

  3. Nov 20

    Anonymous says:

    With the following document schema in one unique collection { "name" : "myObj1"...

    With the following document schema in one unique collection
    {
    "name" : "myObj1" ,
    "testList" : [

    Unknown macro: {"dataType" }

    ,

    Unknown macro: {"dataType" }

    ,

    Unknown macro: {"dataType" }

    ,

    Unknown macro: {"dataType" }

    ,

    Unknown macro: {"dataType" }

    ]
    }

    is it possible to do a query that find an object based on the value that are in the embeeded testList (example : I want all the documents that contains "dataType" : "xxx" in testList) and how ?

    Thanks in advance

    1. Nov 20

      Anonymous says:

      Oh sorry it seems that I forgot something to have my post displayed correctlyWit...

      Oh sorry it seems that I forgot something to have my post displayed correctlyWith the following document schema in one unique collection

      {
       "name" : "myObj1" ,
       "testList" : [ {"dataType" : "xxx", 123}, {"dataType" : "zzz", "value" : 1}, {"dataType" : "xxx", "value" : 32} ]
      }
      

      is it possible to do a query that find an object based on the value that are in the embeeded testList (example : I want all the documents that contains "dataType" : "xxx" in testList) and how ?

      Thanks in advance

      1. Nov 20

        Anonymous says:

        Ok just found the answer to my question we can search in the properties usinf "m...

        Ok just found the answer to my question we can search in the properties usinf "myObject.testList" : "xxx" in a query. With the java driver :

         BasicDBObject filterObj = new BasicDBObject();
         filterObj.put("testList", "xxx");
         DBCursor curs = myCollection.find(filterObj);
        
  4. Nov 29

    Anonymous says:

    Which best practice of updating existing object in mongo db?

    Which best practice of updating existing object in mongo db?

  5. Dec 03

    Anonymous says:

    How do one updates an entire collection? This one worked for me: String MESSAG...

    How do one updates an entire collection?

    This one worked for me:

    String MESSAGE_ACTIONS = ...

    BasicDBObject update = new BasicDBObject("actionsDataStr", MESSAGE_ACTIONS);
    BasicDBObject set = new BasicDBObject("$set", update);
    DBCursor dbCursor = MESSAGES.find(new BasicDBObject());
    while (dbCursor.hasNext()) {
                MESSAGES.update(dbCursor.next(), set);
    }

    However I didn't want to loop the cursor. This code bellow didn't work

    messages.update(new BasicDBObject(), set)

    It had only updated one docuemnt at a time.

    Nor did messages.update(new BasicDBObject(), set, true, true) or messages.updateMulti() helped

  6. Dec 08

    Anonymous says:

    MongoDB is looking very good indeed. I'm just curious about one thing: when usin...

    MongoDB is looking very good indeed. I'm just curious about one thing: when using a RDBMS I can use a DataSource on an Application Server. That way the person maintaining the server is responsible for things like passwords, the address of the database and connection pooling. I don't want those concerns in my code (mostly since it would require changing my code when it migrates from the test environment to production). How could such issues be handled with Mongo?

    Groeten,

    Friso

    1. Dec 09

      Eliot Horowitz says:

      Its a good question! Suggestions welcome I think someone working more closely ...

      Its a good question! Suggestions welcome
      I think someone working more closely with various frameworks might have better ideas on that than I would at the moment.

    2. Dec 16

      Anonymous says:

      One way I can think of is this - since we are using Java you can easily point yo...

      One way I can think of is this - since we are using Java you can easily point your userid's and passwords in a 'encrypted' properties file outside of your application. And pass the location/path to that file/folder via a Java startup property like this:

      -D DBPropHome=/var/ProdResources/DBPropFile.enc

      So when you read that file, you decrypt that data and then apply the userid and password to the code.

  7. Dec 20

    Anonymous says:

    Why is 1 -> ascending? why isn't ascending -> ascending?

    Why is 1 -> ascending? why isn't ascending -> ascending?

  8. Jan 10

    Anonymous says:

    HI { "_id" : "4b4b144f695ae179863e195e" , "fname" : "Thilina" , "mname" : "Isha...

    HI

    { "_id" : "4b4b144f695ae179863e195e" , "fname" : "Thilina" , "mname" : "Ishantha" , "lname" : "Rathnayake" , "info" : { "no" : "89789" , "street" : "oihuh" , "Town" : "hhoihih"} , "_ns" : "testCollection"}

    I want to  quary   "info" : { "no" : "89789"

    how can i do it



    1. Jan 10

      Anonymous says:

      BasicDBObject query = new BasicDBObject(); query.put("info.no", "89789"); cur ...

      BasicDBObject query = new BasicDBObject();

      query.put("info.no", "89789");

      cur = coll.find(query);

      while(cur.hasNext())

      Unknown macro: { System.out.println(cur.next()); }
  9. Jan 21

    Anonymous says:

    Hi, how can I add sort to query? 10x, Dan

    Hi, how can I add sort to query?
    10x,
    Dan

Add Comment