Over a million developers have joined DZone.

Beginner's Walkthrough: MongoDB and Java

DZone's Guide to

Beginner's Walkthrough: MongoDB and Java

Walk through the basic process of MongoDB installation, followed by the creation of a simple CRUD application with Java and MongoDB.

· Database Zone ·
Free Resource

RavenDB vs MongoDB: Which is Better? This White Paper compares the two leading NoSQL Document Databases on 9 features to find out which is the best solution for your next project.  

This tutorial takes you through the basic process of installing MongoDB followed by simple CRUD application with Java and MongoDB.

What's in this tutorial?

  • Installation.

  • Connecting to the Shell.

  • Setting Up Your IDE.

  • Connecting to Your Application.

  • Basic CRUD Operations: Creating a document, saving it to the database, and querying for that same document again.

  • Overview of JVM libraries and how they work with MongoDB.


Use the following installation instructions to install MongoDB 3.2 on Ubuntu 14.04.

Import the public key used by the package management system:

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927

Create a list file for MongoDB:

echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list

Reload local package database:

sudo apt-get update

Install the MongoDB packages:

sudo apt-get install -y mongodb-org=3.2.3 mongodb-org-server=3.2.3 mongodb-org-shell=3.2.3 mongodb-org-mongos=3.2.3 mongodb-org-tools=3.2.3

Check if the MongoDB process has started normally:

ps -ef|grep mongod
netstat -tnlp| grep 27017

If the process hasn’t yet started normally, you should look at the MongoDB logs for any errors and resolve them.

tail /var/log/mongodb/mongod.log

Connecting to the Shell

Connecting to the mongo shell is fairly simple:

Type the command ‘mongo’ at the terminal. This should take you to the mongo shell.

mongo> show dbs
>local  0.000GB

You are ready to interact with MongoDB to perform basic stuff using mongo shell.

Setting Up Your IDE

I have used the Eclipse Helios IDE for this tutorial. You can use the IDE of your choice. Download Eclipse here.

Launch the Eclipse IDE using the eclipse executable that comes with the download.

Create new project MongoDB_CRUD within IDE using New->Java Project.

Connecting to Your Application

Download the required drivers:

Add drivers to your classpath. Add drivers downloaded in the previous step to your application using:

Project->Build Path->Configure Buid Path-> Add External Jars

Connect to MongoDB. Include the following import statements:

import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;

Connect to the MongoDB instance running localhost port 27017 by creating an instance of MongoClient as:

MongoClient mongoClient = new MongoClient();

On successfully connecting to MongoDB, you can access the database:

MongoDatabase db = mongoClient.getDatabase(“CRUD”);

Note: The database CRUD would be created after we insert the first document in any of its collections.

Basic CRUD Operations

In this sample application, we create a database CRUD. This database contains the collection courses, which stores sample information from courses from MongoDB University.

  1. Insert: You can use the insertOne() method to insert a document into a collection in MongoDB. If the collection into which you’re inserting a document does not exist, the collection is created on the fly.

Create an instance of Document and append the key and values to document:

Document course=new Document();
course.append("courseID", "M101P");course.append("title", "MongoDB for Developers");course.append("startDate", "15 Mar 2016 at 17:00 UTC");course.append("endDate", "03 May 2016 at 17:00 UTC");course.append("instructor","Andrew Erlichson");course.append("aboutCourse", "Learn everything you need to know to get started building a MongoDB-based app");

Run the application and check if the document was inserted into the collection courses using the mongo shell:

mongo> show dbs
CRUD   0.000GB
local  0.000GB
test   0.000GB
> use CRUD
switched to db 
CRUD> show collections
> db.courses.findOne()
{ "_id" : ObjectId("56d2ce10a67a5623a00d470c"), 
  "courseID" : "M101P", 
  "title" : "MongoDB for Developers", 
  "startDate" : "15 Mar 2016 at 17:00 UTC", 
  "endDate" : "03 May 2016 at 17:00 UTC", 
  "instructor" : "Andrew Erlichson", 
  "aboutCourse" : "Learn everything you need to know to get started building a MongoDB-based app"}

We’ve successfully inserted a document into the collection courses.

Insert a few more documents in the courses collection.

2. Read: You can use the find() method to read or retrieve documents from MongoDB. You can query to find the specific document from a collection or to get all documents from the collection.

To find all documents in the collection, use the find() method with criteria. This returns to you the cursor in the form of FindIterable.

FindIterable<Document> docs= db.getCollection("courses").find();
for(Document d: docs){System.out.println(d);}

It prints following documents to console:

{ “_id” : { “$oid” : “56d2ce10a67a5623a00d470c” }, “courseID” : “M101P”, “title” : “MongoDB for Developers”, “startDate” : “15 Mar 2016 at 17:00 UTC”, “endDate” : “03 May 2016 at 17:00 UTC”, “instructor” : “Andrew Erlichson”, “aboutCourse” : “Learn everything you need to know to get started building a MongoDB-based app” }
{ “_id” : { “$oid” : “56d2cfcca67a562438eeeb5b” }, “courseID” : “M102”, “title” : “MongoDB for DBAs”, “startDate” : “15 Mar 2016 at 17:00 UTC”, “endDate” : “03 May 2016 at 17:00 UTC”, “instructor” : “Dwight Merriman”, “aboutCourse” : “Learn everything you need to know to administer a MongoDB installation in production..” }

3. Update: You can update single or many documents using updateOne() and updateMany() methods respectively. The following example updates document with “courseID” : “M101P” , sets “endDate” : “04 May 2016 at 17:00 UTC”

db.getCollection(“courses”).updateOne(new Document(“courseID”, “M101P”),new Document(“$set”, new Document(“endDate”, “04 May 2016 at 17:00 UTC”)));

The results can be verified using mongo shell:

db.courses.findOne({“courseID” : “M101P”})
{ “_id” : ObjectId(“56d2ce10a67a5623a00d470c”), 
 “courseID” : “M101P”, 
 “title” : “MongoDB for Developers”, 
 “startDate” : “15 Mar 2016 at 17:00 UTC”, 
 “endDate” : “04 May 2016 at 17:00 UTC”, 
 “instructor” : “Andrew Erlichson”, 
 “aboutCourse” : “Learn everything you need to know to get started building a MongoDB-based app”

4. Delete: You can use deleteOne() or deletedMany() to delete single and multiple documents from collection respectively. The following code snippet deletes one document with matching criteria.

db.getCollection(“courses”).deleteOne(new Document(“title”, “MongoDB for DBAs”));

Mongodb now returns only single document from courses collection since document with “title” : “MongoDB for DBAs” deleted.

Overview of JVM Libraries and How They Work With MongoDB

Following are some JVM libraries that are used with MongoDB to provide high-level interactions to MongoDB using Java and make your job lot easier.


This was a getting started guide for beginners with MongoDB and Java. You can start building real world applications using the ORM’s for MongoDB and Java.

Do you pay to use your database? What if your database paid you? Learn more with RavenDB.

mongodb ,java ,database ,crud

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}