1. Overview

In this article, we’ll have a look at integrating MongoDB, a very popular NoSQL open source database with a standalone Java client.

MongoDB is written in C++ and has quite a number of solid features such as map-reduce, auto-sharding, replication, high availability etc.

2. MongoDB

Let’s start with a few key points about MongoDB itself:

  • stores data in JSON-like documents that can have various structures
  • uses dynamic schemas, which means that we can create records without predefining anything
  • the structure of a record can be changed simply by adding new fields or deleting existing ones

The above-mentioned data model gives us the ability to represent hierarchical relationships, to store arrays and other more complex structures easily.

3. Terminologies

Understanding concepts in MongoDB becomes easier if we can compare them to relational database structures.

Let’s see the analogies between Mongo and a traditional MySQL system:

  • Table in MySQL becomes a Collection in Mongo
  • Row becomes a Document
  • Column becomes a Field
  • Joins are defined as linking and embedded documents

This is a simplistic way to look at the MongoDB core concepts of course, but nevertheless useful.

Now, let’s dive into implementation to understand this powerful database.

4. Maven Dependencies

We need to start by defining the dependency of a Java Driver for MongoDB:

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver-sync</artifactId>
    <version>4.8.2</version>
</dependency>

To check if any new version of the library has been released – track the releases here.

5. Using MongoDB

Now, let’s start implementing Mongo queries with Java. We will follow with the basic CRUD operations as they are the best to start with.

5.1. Make a Connection With MongoClient

First, let’s make a connection to a MongoDB server. With version >= 2.10.0, we’ll use the MongoClient:

MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");

And for older versions use Mongo class:

Mongo mongo = MongoClients.create("mongodb://localhost:27017");

5.2. Connecting to a Database

Now, let’s connect to our database. It is interesting to note that we don’t need to create one. When Mongo sees that database doesn’t exist, it will create it for us:

MongoDatabase database = mongoClient.getDatabase("myMongoDb");

Sometimes, by default, MongoDB runs in authenticated mode. In that case, we need to authenticate while connecting to a database.

We can do it as presented below:

MongoClient mongoClient = MongoClients.create();
MongoDatabase database = mongoClient.getDatabase("myMongoDb"); In case you have a database with user and password you will have to use MongoClientSettings to set your username and password to that database.

5.3. Show Existing Databases

Let’s display all existing databases. When we want to use the command line, the syntax to show databases is similar to MySQL:

show databases;

In Java, we display databases using snippet below:

mongoClient.listDatabasesNames().forEach(System.out::println);

The output will be:

local      0.000GB
myMongoDb  0.000GB

Above, local is the default Mongo database.

5.4. Create a Collection

Let’s start by creating a Collection (table equivalent for MongoDB) for our database. Once we have connected to our database, we can make a Collection as:

database.createCollection("customers");

Now, let’s display all existing collections for current database:

database.listCollectionNames().forEach(System.out::println);

The output will be:

customers

5.5. Save – Insert

The save operation has save-or-update semantics: if an id is present, it performs an update, if not – it does an insert.

When we save a new customer:

MongoCollection<Document> collection = database.getCollection("customers");
Document document = new Document();
document.put("name", "Shubham");
document.put("company", "Baeldung");
collection.insertOne(document);

The entity will be inserted into a database:

{
    "_id" : ObjectId("33a52bb7830b8c9b233b4fe6"),
    "name" : "Shubham",
    "company" : "Baeldung"
}

Next, we’ll look at the same operation – save – with update semantics.

5.6. Save – Update

Let’s now look at save with update semantics, operating on an existing customer:

{
    "_id" : ObjectId("33a52bb7830b8c9b233b4fe6"),
    "name" : "Shubham",
    "company" : "Baeldung"
}

Now, when we save the existing customer – we will update it:

Document query = new Document();
query.put("name", "Shubham");

Document newDocument = new Document();
newDocument.put("name", "John");

Document updateObject = new Document();
updateObject.put("$set", newDocument);

collection.updateOne(query, updateObject);

The database will look like this:

{
    "_id" : ObjectId("33a52bb7830b8c9b233b4fe6"),
    "name" : "John",
    "company" : "Baeldung"
}

As you can see, in this particular example, save uses the semantics of update, because we use object with given _id.

5.7. Read a Document From a Collection

Let’s search for a Document in a Collection by making a query:

Document searchQuery = new Document();
searchQuery.put("name", "John");
FindIterable<Document> cursor = collection.find(searchQuery);
try (final MongoCursor<Document> cursorIterator = cursor.cursor()) {
    while (cursorIterator.hasNext()) {
        System.out.println(cursorIterator.next());
    }
}
It will show the only Document we have by now in our Collection:
[
    {
      "_id" : ObjectId("33a52bb7830b8c9b233b4fe6"),
      "name" : "John",
      "company" : "Baeldung"
    }
]

5.8. Delete a Document

Let’s move forward to our last CRUD operation, deletion:

Document searchQuery = new Document();
searchQuery.put("name", "John");

collection.deleteOne(searchQuery);

With above command executed, our only Document will be removed from the Collection.

6. Conclusion

This article was a quick introduction to using MongoDB from Java.

The implementation of all these examples and code snippets can be found over on GitHub – this is a Maven based project, so it should be easy to import and run as it is.

Course – LSD (cat=Persistence)

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:

>> CHECK OUT THE COURSE
res – Persistence (eBook) (cat=Persistence)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.