In this tutorial, we will show you how to develop a simple Java application to connect MongoDB database and perform query, insert, update and delete operations using MongoDB Java driver.
What We Used
- Oracle JDK 1.8
- Apache Maven 3.3.9
- MongoDB 3.2.9
- MongoDB Java Driver 3.2.2
1. Create Java Project
Execute the following command to create a simple Java project with Maven:
mvn archetype:generate
-DarchetypeArtifactId=maven-archetype-quickstart
-DgroupId=com.chankok.mongodb
-DartifactId=java-mongodb
-Dversion=1.0.0
-Dpackage=com.chankok.mongodb
-DinteractiveMode=false
Maven will automatically create the following Java classes, you have to remove it manually from the project folder:
com.chankok.mongodb.App.java
com.chankok.mongodb.AppTest.java
2. Edit pom.xml
Add MongoDB Java driver dependency in pom.xml
.
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<name>java-mongodb</name>
<groupId>com.chankok.mongodb</groupId>
<artifactId>java-mongodb</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.3.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
3. Connect to MongoDB
Connect to the local MongoDB server with default port 27017
.
MongoClient mongoClient = new MongoClient();
Connect to the MongoDB server with specific host and port.
MongoClient mongoClient = new MongoClient("192.168.0.1", 27018);
Connect to the MongoDB server using MongoDB connection URI.
MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
4. Get Database
Get the test
database.
MongoDatabase testDatabase = mongoClient.getDatabase("test");
5. Get Collection
Get the users
collection.
MongoCollection usersCollection = database.getCollection("users");
6. Insert Data
Insert a new user
document into the users
collection.
Document user = new Document("username", "chankok")
.append("password", "1234567")
.append("email", "chankok@email.com");
usersCollection.insertOne(user);
Tip: If the collection does not exists in database, this operation will create the collection.
7. Query Data
Find the user document by document ID _id
using Filters
class eq
method.
Document user = usersCollection.find(eq("_id", id)).first();
8. Update Data
Update the user
document where it equal to the specific document ID with new password
.
Document user = new Document("password", "7654321");
usersCollection.updateOne(eq("_id", id), new Document("$set", user));
9. Delete Data
Delete a user
document where it equal to the specific document ID.
usersCollection.deleteOne(eq("_id", id));
10. Close Connection
Close the MongoDB connection.
mongoClient.close();
11. Run Application
Execute the following command to run the application:
mvn compile exec:java
-Dexec.mainClass=com.chankok.mongodb.Application
-Dexec.cleanupDaemonThreads=false
Java Codes
UserDao.java
package com.chankok.mongodb;
import org.bson.Document;
import org.bson.types.ObjectId;
import com.mongodb.MongoWriteException;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import static com.mongodb.client.model.Filters.eq;
public class UserDao {
private final MongoCollection usersCollection;
public UserDao(final MongoDatabase database) {
// Get users collection
usersCollection = database.getCollection("users");
}
/*
* Insert new user
*/
public Document addUser(String username, String password, String email) {
Document user = new Document("username", username)
.append("password", password)
.append("email", email);
try {
usersCollection.insertOne(user);
} catch (MongoWriteException e) {
e.printStackTrace();
return null;
}
return user;
}
/*
* Find user by ID
*/
public Document findUser(ObjectId id) {
Document user = usersCollection.find(eq("_id", id)).first();
return user;
}
/*
* Update user
*/
public void updateUser(ObjectId id, Document user) {
usersCollection.updateOne(eq("_id", id), new Document("$set", user));
}
/*
* Delete user
*/
public void deleteUser(ObjectId id) {
usersCollection.deleteOne(eq("_id", id));
}
}
Application.java
package com.chankok.mongodb;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoDatabase;
/**
* A simple MongoDB application
* - Connecting to MongoDB database
* - Perform query, insert, update and delete operations
*
* @author chankok
*/
public class Application {
/**
* Main method to start the MongoDB application
*
* @param args
*/
public static void main(String[] args) {
new Application();
}
public Application() {
try {
// Connect to MongoDB
MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
//MongoClient mongoClient = new MongoClient();
System.out.println("Connect to MongoDB");
// Get database
MongoDatabase testDatabase = mongoClient.getDatabase("test");
System.out.println("Get test database");
// User collection DAO
UserDao userDao = new UserDao(testDatabase);
System.out.println("Get users collection");
// Insert new user
Document addedUser = userDao.addUser("chankok", "1234567", "chankok@email.com");
System.out.println("Insert user: " + addedUser);
// Find new added user by ID
Document user = userDao.findUser(addedUser.getObjectId("_id"));
System.out.println("Find user: " + user);
// Update user password
userDao.updateUser(user.getObjectId("_id"), new Document("password", "7654321"));
// Find updated user by ID
Document updatedUser = userDao.findUser(user.getObjectId("_id"));
System.out.println("Updated user: " + updatedUser);
// Delete user
userDao.deleteUser(updatedUser.getObjectId("_id"));
// Close MongoDB client
mongoClient.close();
System.out.println("Close MongoDB connection");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output
The following output will be generated:
Connect to MongoDB
Get test database
Get users collection
Insert user: Document{{username=chankok, password=1234567, email=chankok@email.com, _id=5806422e31cc0e04701fcde8}}
Find user: Document{{_id=5806422e31cc0e04701fcde8, username=chankok, password=1234567, email=chankok@email.com}}
Updated user: Document{{_id=5806422e31cc0e04701fcde8, username=chankok, password=7654321, email=chankok@email.com}}
Close MongoDB connection
Project Directory Structure
The project directory structure should look as follows:
Summary
Congratulation! You have learned how to connect to MongoDB server and perform query, insert, update, delete operations using MongoDB Java driver.