MongoDB is a NoSQL database that allows us to store complex, unstructured data types. In this tutorial, I will walk you through the basic steps to work with MongoDB in your Java applications.
First, I will create a new Maven project as an example:
Similar to other database systems, in order to work with Java, we need to declare to use the MongoDB driver in our application.
1 2 3 4 5 |
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver</artifactId> <version>3.6.3</version> </dependency> |
OK, let’s get started.
To connect to MongoDB, we will use the MongoClient object from its Driver library with the following declaration:
1 2 |
MongoClientURI uri = new MongoClientURI("mongodb://localhost:27017"); MongoClient client = new MongoClient(uri); |
Where the MongoClientURI object is the object that will manage the MongoDB information including the IP address and port that MongoDB is running. The MongoClient object will be the object responsible for connecting to MongoDB.
In case you are using MongoDB server with authentication mode, then you need to declare username and password are assigned to the database that you are going to use.
1 2 3 |
MongoCredential credential = MongoCredential.createCredential("khanh", "mongodb", "abc123".toCharArray()); List<MongoCredential> auths = new ArrayList<MongoCredential>(); auths.add(credential); |
Then, connect to MongoDB with the following code:
1 2 |
ServerAddress serverAddress = new ServerAddress("localhost", 27017); MongoClient client = new MongoClient(serverAddress, auths); |
I will use MongoDB server without authentication mode in this tutorial.
By default, MongoDB will run on port 27017 and if you are installing MongoDB on your local machine then we do not need to declare the MongoClientURI object. You simply declare the following:
1 |
MongoClient client = new MongoClient(); |
I’m using MongoDB on my machine so I just declare it like that!
At this point, if you run the application:
1 2 3 4 5 6 7 8 9 10 |
package com.huongdanjava.mongodb; import com.mongodb.MongoClient; public class Application { public static void main(String[] args) { MongoClient client = new MongoClient(); } } |
You will see the following results:
Look at the log, you can see that our application is connected to MongoDB.
Once connected to MongoDB, now you can work with it.
First, you can get a list of existing databases in your current MongoDB using the listDatabaseNames() method.
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package com.huongdanjava.mongodb; import com.mongodb.MongoClient; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoIterable; public class Application { public static void main(String[] args) { MongoClient client = new MongoClient(); MongoIterable<String> databaseNames = client.listDatabaseNames(); MongoCursor<String> iterator = databaseNames.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } } |
Result:
We can select the database to use the getDatabase() method of the MongoClient object.
For example, if I have a database called mongodb in MongoDB, my code will look like this:
1 |
MongoDatabase mongodb = client.getDatabase("mongodb"); |
Just like when using the command line with MongoDB, if the database we choose to manipulate does not exist, this database will be automatically created.
MongoDatabase object will hold all information about the Collections in the database that we are using. Therefore, from this MongoDatabase object, you can get the names of all Collections using the listCollectionNames() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.huongdanjava.mongodb; import com.mongodb.MongoClient; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; import com.mongodb.client.MongoIterable; public class Application { public static void main(String[] args) { MongoClient client = new MongoClient(); MongoDatabase mongodb = client.getDatabase("mongodb"); MongoIterable<String> collectionNames = mongodb.listCollectionNames(); MongoCursor<String> iterator = collectionNames.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } } |
My database “mongodb” is having the following Collections:
The result would be:
To work with a Collection, you can use the getCollection() method of the MongoDatabase object to get the MongoCollection object for the Collection.
My example is as follows:
1 |
MongoCollection<Document> student = mongodb.getCollection("student"); |
If you want to insert a Document into the Collection you can use the insertOne() method to insert a Document or insertMany() to insert multiple Documents at the same time.
A Document is a JSON string and we will use the Document object of the MongoDB Driver API to build it. For example, now I want to build a Document of student information including name and age, I will create Document object as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
package com.huongdanjava.mongodb; import org.bson.Document; public class Student extends Document { private static final String NAME = "name"; private static final String AGE = "age"; public static final String COLLECTION_NAME = "student"; public String getName() { return getString(NAME); } public void setName(String name) { put(NAME, name); } public Integer getAge() { return getInteger(AGE); } public void setAge(Integer age) { put(AGE, age); } } |
then write code to insert a new Document:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package com.huongdanjava.mongodb; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; public class Application { public static void main(String[] args) { MongoClient client = new MongoClient(); MongoDatabase mongodb = client.getDatabase("mongodb"); MongoCollection<Document> studentCollection = mongodb.getCollection(Student.COLLECTION_NAME); Student student = new Student(); student.setName("Khanh"); student.setAge(31); studentCollection.insertOne(student); } } |
Result:
Of course, you can also check the result from the code by using the find() method of the MongoCollection object.
This find() method has a Document object argument, which is the criteria for finding all the Documents in the current Collection with similar content.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
package com.huongdanjava.mongodb; import com.mongodb.MongoClient; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; import org.bson.Document; public class Application { public static void main(String[] args) { MongoClient client = new MongoClient(); MongoDatabase mongodb = client.getDatabase("mongodb"); MongoCollection<Document> studentCollection = mongodb.getCollection(Student.COLLECTION_NAME); Student student = new Student(); student.setName("Khanh"); student.setAge(31); FindIterable<Document> documents = studentCollection.find(student); MongoCursor<Document> iterator = documents.iterator(); while (iterator.hasNext()) { Document next = iterator.next(); System.out.println(next); } } } |
In the example above, I looked for the Student Document in terms of name and age. You can expand the search results by one of these two criteria also.
Result:
You can also update one or more Documents at the same time.
We will use the updateOne() or updateMany() methods of the MongoCollection object to do this.
There are many methods of overloading these two methods with different parameters. But basically, there are two main parameters, the Document object to find the Document need to update, the second Document object contains the content to update.
In my example, suppose I need to update the age of students named Khanh to 32, then I will write the code as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
package com.huongdanjava.mongodb; import com.mongodb.MongoClient; import com.mongodb.client.*; import org.bson.Document; public class Application { public static void main(String[] args) { MongoClient client = new MongoClient(); MongoDatabase mongodb = client.getDatabase("mongodb"); MongoCollection<Document> studentCollection = mongodb.getCollection(Student.COLLECTION_NAME); Student studentFilter = new Student(); studentFilter.setName("Khanh"); Student student = new Student(); student.setAge(32); Document updateObject = new Document(); updateObject.put("$set", student); studentCollection.updateOne(studentFilter, updateObject); } } |
As you can see, the Document object containing the content to be updated needs to be built with the keyword “$ set” and its value is the information the student needs to update.
Result:
And you can also delete one or more documents at once using the deleteOne() and deleteMany() methods.
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package com.huongdanjava.mongodb; import com.mongodb.MongoClient; import com.mongodb.client.*; import com.mongodb.client.result.DeleteResult; import org.bson.Document; public class Application { public static void main(String[] args) { MongoClient client = new MongoClient(); MongoDatabase mongodb = client.getDatabase("mongodb"); MongoCollection<Document> studentCollection = mongodb.getCollection(Student.COLLECTION_NAME); Student student = new Student(); student.setName("Khanh"); DeleteResult deleteResult = studentCollection.deleteOne(student); System.out.println(deleteResult.getDeletedCount()); } } |
Result: