MongoDB Hello World — How to connect, insert and find data

Gonçalo Lourenço
2 min readJun 9, 2018

--

“Two books on a desk near a MacBook with lines of code on its screen” by Émile Perron on Unsplash

When you have a huge environment, with hundreds of micro services, and need to rapidly grow in order to continue giving the best user experience, and avoid congestion problems that will lead to high CPU and memory usage, you can have different approaches: Vertical or Horizontal scaling. Vertical scaling will give you more computational power by upgrading hardware components, this can be a good solution, but there’s physical limitations and high costs associated. Horizontal scaling allows you to add more computational power by adding more servers side by side. The problem is, how do you approach this when the problem is data? Is there a way to easily scale horizontally a database? MongoDB came to save the day.

This is a simple Hello World example of how to insert and find data from MongoDB using Java.

First, make sure you import a compatible version of MongoDB Java Driver for your MongoDB version. I’m using mongodb-driver-3.5.0, to connect my local MongoDB in version 3.2.

In Java, use MongoClient to connect to your MongoDB, then select the Database and Collection:

Let’s start by inserting some data, for example:

{
“name”:”lourenco”,
“country”:”USA”
}

In Java, we’ll create a new org.bson.Document and insert it into our MongoDB:

The System.out.println will output the previous JSON example. And the insertOne will insert the Document we’ve just created.

In some cases, it’s useful to insert many documents at the same time. You can do it this way:

To retrieve data, use the function find() that returns an Iterable variable of Documents:

This will output all Documents stored in our collection:

{ “_id” : { “$oid” : “59961f1a6b98423afc092841” }, “name” : “Lourenco”, “country” : “USA” }
{ “_id” : { “$oid” : “59961f1a6b98423afc092842” }, “name” : “John”, “country” : “USA” }

Let’s find a specific entry, for example name=Lourenco. Create a new Document matching the entry you want to find.
This way:

Here’s the entire code, you can also find it in my GitHub.

--

--