>> CHECK OUT THE COURSE
1. OverviewIn this article, we’ll have a look atintegrating 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.MongoDBLet’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 meansthat wecan create records without predefining anything the structure of a record can be changed simply by adding new fields or deleting existing onesThe above-mentioneddata model gives usthe ability to represent hierarchical relationships, to store arrays and other more complex structures easily.
3.TerminologiesUnderstanding 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 definedas linking and embedded documentsThis is a simplistic way to look at the MongoDB core concepts of course, but nevertheless useful.
Now, let’s dive into implementationto understand this powerful database.
4.Maven DependenciesWe need to start by defining the dependency of aJava Driver for MongoDB:
<dependency><groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.4.1</version>
</dependency>
To check if any new version of the library has been released track the releases here .
5. Using MongoDBNow, 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 MongoClientFirst, let’s make a connection to a MongoDB server. Withversion>= 2.10.0, we’ll use the MongoClient :
MongoClient mongoClient = new MongoClient("localhost", 27017);And for older versions use Mongo class:
Mongo mongo = new Mongo("localhost", 27017); 5.2. Connecting to a DatabaseNow, 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 itfor us:
DB database = mongoClient.getDB("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 = new MongoClient();DB database = mongoClient.getDB("myMongoDb");
boolean auth = database.authenticate("username", "pwd".toCharArray()); 5.3.Show Existing Databases
Let’s display all existing databases. When we want to use command line, the syntaxto show databases is similarto MySQL:
show databases;In Java, we display databases using snippet below:
mongoClient.getDatabaseNames().forEach(System.out::println);The output will be:
local 0.000GBmyMongoDb 0.000GB
Above, local is the default Mongo database.
5.4.Create a CollectionLet’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", null);Now, let’s display all existing collections for current database:
database.getCollectionNames().forEach(System.out::println);The output will be:
customers 5.5. Save InsertThe 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:
DBCollection collection = database.getCollection("customers");BasicDBObject document = new BasicDBObject();
document.put("name", "Shubham");
document.put("company", "Baeldung");
collection.insert(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 UpdateLet’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:
BasicDBObject query = new BasicDBObject();query.put("name", "Shubham");
BasicDBObject newDocument = new BasicDBObject();
newDocument.put("name", "John");
BasicDBObject updateObject = new BasicDBObject();
updateObject.put("$set", newDocument);
collection.update(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 CollectionLet’ssearch for a Document in a Collection by making a query:
BasicDBObject searchQuery = new BasicDBObject();searchQuery.put("name", "John");
DBCursor cursor = collection.find(searchQuery);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
It will showthe 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:
BasicDBObject searchQuery = new BasicDBObject();searchQuery.put("name", "John");
collection.remove(searchQuery); With above command executed, our only