JavaData & JavaNoSQL in Practice with a CRUD Application in Java

NoSQL in Practice with a CRUD Application in Java content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Creating a CRUD application in Java and MongoDB is pretty simple to begin with, although there are many intricacies involved as we dive deeper. The architectural foundation of the MongoDB JDBC library (version 3) quite aligns with the need of the Java developer. The API is intuitive and performs well with document schema that are translated in BSON. The JDBC driver version 3 has substantial changes in the API than its older (version 2) counterpart. So, the code written for one version can be significantly different than the other. Here, we mainly follow version 3 (the latest is v3.2.1 to be specific as of writing this article) APIs while creating a CRUD application in Java. The article gives you a glance at the practical aspects of NoSQL when implemented in MongoDB and Java.

A Glimpse into MongoDB

MongoDB is a document-oriented NoSQL database. If you are familiar with any relational databases, such as an RDBMS package, what a record is to relational database, a document is to MongoDB. Similarly, what a table is to relational database, a collection is to MongoDB. A data item in a document is structured as a key-value pairs much like a JSON object. The value can be of varied type. It may be a string, numbers, arrays, other document, or an array of documents. Thus, a typical document and a collection may be as follows:

Figure 1: The document/collection connection

CRUD in a Mongo Shell

Before going into Java code, let’s first walk through CRUD operations in the mongo shell. Once MongoDB has been installed properly (see installation instructions), it provides an interactive shell called mongo. This shell can be invoked when required to directly interact with the database. The core database process, a daemon called mongod, must be up and running by invoking the mongo console. It can be executed as follows (unless mongod is already running):

mongod --port 27017 -dbpath /usr/local/db/mongodb

The number 27017 signifies the default port number of MongoDB and the path is where the actual database files are kept.

Start the console. Because no user is defined initially, we shall create one subsequently. Until then, simply open the console.


List the name of an available database:

>show dbs

Create a database administrator:

   user: "mano"
   pwd: "abc123"
   roles: [{
      role: "userAdminAnyDatabase"
      db: "admin"

Restart mongod to reflect the changes as

mongod --auth --config /usr/local/etc/mongod.conf

Now, log in to the mongo shell as follows (change ‘user‘ and ‘abc123‘ according to your choice):

mongo -u user -p abc123 --authenticationDatabase admin

Once logged in, create the mydb database. This database shall contain a document collection which, in our case, is library.

>use mydb

Create Document

   "title": "Discrete Mathematics",
   "isbn": "321-543-987",
   "authors": ["Kolman", "Busby", "Ross"],
   "category": ["discrete math", "math"]

Read Document

>db.library.find({category="math", author="coleman"})

Update Document

>db.library.updateOne({ isbn: "123-456-789"},
   {$set:{title:"Compiler Design"}},{upsert:false})

Delete Document


Given, the preceding are very rudimentary CRUD operations executed from a mongo shell. Now, let’s see how we can achieve the same CRUD effect through Java code.

CRUD Application in Java

It is pretty simple to code a rudimentary CRUD implementation in Java. Before delving into the code, download the JDBC driver and include the JAR file in the project build path, or follow the installation guide.

Observe that the code, in essence, is somewhat similar to database access in a relational model, although the underlying principle is very different.

package org.mano.example;

import java.util.Arrays;
import java.util.List;

import org.bson.Document;

import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;

public class CRUD {

   private final static String HOST = "localhost";
   private final static int  PORT = 27017;
   private final static String DATABASE = "mydb";
   private final static String USER = "user";
   private final static String PASSWORD = "abc123";

   private MongoCredential mongoCredential;
   private MongoClient mongoClient;

   public CRUD() {
      mongoCredential = MongoCredential.createCredential
         (USER, DATABASE, PASSWORD.toCharArray());
      mongoClient = new MongoClient(new ServerAddress
         (HOST, PORT), Arrays.asList(mongoCredential));

   public void create(String title, String isbn,
         List<String> authors, List<String> category) {
      try {
         .getCollection("library").insertOne(new Document()
         .append("tite", title).append("isbn", isbn)
         .append("authors", authors).append("category", category));
      } catch (Exception ex) {

   public void readAll() {
      try {
         FindIterable<Document> iter = mongoClient

         iter.forEach(new Block<Document>() {
            public void apply(Document doc) {

      } catch (Exception ex) {

   public void updateCategory(String isbn, List<String> category) {

      try {
         .updateOne(new Document("isbn", isbn),
         new Document("$set", new Document("category", category)));

      } catch (Exception ex) {

   public void delete(String isbn) {

      try {
         .deleteOne(new Document("isbn", isbn));

      } catch (Exception ex) {


package org.mano.example;

import java.util.Arrays;

public class MongoDBCRUDExample {
   public static void main(String[] args) {
      CRUD c=new CRUD();
      c.create("Introduction to Software Engineering", "102-304-506",
         Arrays.asList("Jalote", "Ansari"),
         Arrays.asList("software", "software engineering"));
      c.create("Numerical Analysis", "999-888-777",
         Arrays.asList("Moulah", "Kabir"),
         Arrays.asList("math", "numerical"));
         Arrays.asList("mathematics","numerical", "computation"));
Note: Refer to the MongoDB CRUD guide for further details on the intricacies involved in Java implementation.


The article tried to give you a hands-on example of how to leverage Java and MongoDB with the help of a CRUD example without delving into much conceptual detail. The JDBC API library is highly intuitive and quite straightforward in dealing with connectivity as well as data manipulation through API functions. The intuitive appeal does not get diminished at all even as we go deeper into the complexities of a CRUD application. We shall see some aspects of it in the next few articles.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories