How to Query MongoDB® using Java


Overview

MongoDB is an open source document-oriented database that stores data as BSON (a binary-encoded serialization of Java Script Object Notation (JSON)) documents and supports dynamic data with no fixed schemas rather than relational tables. Interacting with MongoDB (a NoSQL system) is not done using SQL but rather using query APIs for various languages.

This article will cover how to access MongoDB using the Java driver. Another tutorial covers how to access MongoDB using a JDBC driver and SQL.


Step-by-Step JDBC Configuration

  1. Download Java Driver
  2. Put Driver in Classpath
  3. Establish A Connection
  4. Get Database
  5. Get Collections
  6. Getting A Single Document
  7. Getting Multiple Documents
  8. Inserting Documents
  9. Save, Update, Find, Delete

For more information, check out our Helpful Links and References.


Download MongoDBJava Driver

The first thing you will need to do is download the MongoDB Java Driver. Click here to download.


Put Driver in Classpath

Once you've downloaded the Java driver, put the JAR in your Java CLASSPATH. A common location is in the <JRE_HOME>\lib\ext folder of your Java JRE installation.


Establish A Connection

To make a connection, we will need to use the MongoClient class instance. The MongoClient class is thread safe which means only one instance is needed even if multiple threads are being used. (see the concurrency doc for more info).

Note: You will need to know the IP address and port of the database you wish to connect to. If the database does not exist, MongoDB will create it for you.

Use the following code to make your connection.

import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;

MongoClient mongoClient = new MongoClient( "localhost" , 27017 );

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

User authentication

If you are running MongoDB in secure mode you will need user authentication to complete the connection. If so, use the following sample code:

MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB("test");
boolean auth = db.authenticate(myUserName, myPassword);

To clean up your resources and dispose of an instance call:

mongoClient.close();

Get Database

Once a connection is established you can then use the getDB() method to get a database by name.

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

To display all databases:

List dbs = mongo.getDatabaseNames();
for(String db : dbs)
{
	System.out.println(db);
}

Getting Collections

Getting collections is a key step to being able to query and manipulate data. You can retrieve a colleciton by name using getCollection().

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

To retrieve a list of collection names in the database:

Set colls = db.getCollectionNames();

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

Getting A Single Document

If you want to retrieve a single document from a collection you can use the find() method.

For Example: If you want to find the document for which the value of "i" is 52, we can use the following:

BasicDBObject query = new BasicDBObject("i", 52);

cursor = coll.find(query);

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

Note that $ operators used within MongoDB documentation are represented as DBObjects when using the Java driver. Example:

db.things.find({j: {$ne: 3}, k: {$gt: 10} });


Getting Multiple Documents

Multiple documents can be retrieved using a condition built from BasicDBObject. This example will return all documents where i > 52.

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

cursor = coll.find(query);

Inserting Documents

Once you have your collection object you can then choose to insert documents by byuilding a BasicDBObject.

The following sample code is an example of a JSON document.

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

To build this using the BasicDBObject you need to use the insert() method to add it to the collection.

BasicDBObject doc = new BasicDBObject("name", "MongoDB").
                              append("type", "database").
                              append("count", 1).
                              append("info", new BasicDBObject("x", 203).append("y", 102));

coll.insert(doc);

Save, Update, Find, & Delete

The following examples demonstrate how to save, update, find, and delete documents.

Save (Insert) a document

DBCollection col = db.getCollection("mycol");
BasicDBObject doc = new BasicDBObject();
doc.put("name", "Joe Smith");
doc.put("age", 25);
doc.put("createdDate", new Date());
col.insert(document);

Update a document:

DBCollection col = db.getCollection("mycol");

BasicDBObject query = new BasicDBObject();
query.put("name", "MongoDB");

BasicDBObject newDocument = new BasicDBObject();
newDocument.put("name", "MongoDB-updated");

BasicDBObject updateObj = new BasicDBObject();
updateObj.put("$set", newDocument);

col.update(query, updateObj);

More info

Perform a query and list matching documents:

DBCollection col = db.getCollection("mycol");

BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", "Joe Smith");		// Find documents with Joe Smith in name field

DBCursor cursor = table.find(searchQuery);

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

Delete documents that match a given criteria:

DBCollection table = db.getCollection("user");

BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", "Joe Smith");		// Find documents with Joe Smith in name field

table.remove(searchQuery);	// Delete those matching documents

Helpful Links

  • MongoDB API Documentation
  • MongoDB Java Driver From GitHub

  • References

    1. Mammatus. "Installing MongoDB Database to Work with Java (MongoDB Java Tutorial)". NoSQL & MongoDB Training.
    2. MongoDB. "Getting Started with Java Driver". 10gen Inc.
    3. Mkyong. "Java + MongoDB".

    Need help?
    Unity Data will turn your data into business value. Contact us for a free consultation.