In this tutorial we will learn how to work with the MongoDB database using java.
Create an empty project and connect the dependencies.
First, add the java mongodb library.
Since version 3.0, the dependency structure has changed slightly, a synchronous and asynchronous version of the driver appeared. In this article, we’ll look at working with a synchronous library.
1 2 3 4 5 6 7 |
<dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver</artifactId> <version>3.4.2</version> </dependency> </dependencies> |
Let’s start working with the database.
1. Establishing a connection
First we create a connection to MongoDB
1 |
MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://192.168.4.103:27017")); |
MongoClient can also be created simply by specifying the port and host separately
1 |
MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); |
2. Connection to the database
To connect to the MongoDB database, you need to create an instance of MongoDatabase. An important feature, if the database to which you are connecting does not exist, MongoDB will create it when the data is first saved.
1 |
MongoDatabase db = mongoClient.getDatabase("clients"); |
3. Working with collections
After creating the MongoDatabase instance, use the getCollection()
method to work with collections.
1 |
MongoCollection<Document> c = db.getCollection("client_info"); |
If the collection does not exist, it will be created immediately after you save the data. MongoCollection instances are immutable.
4. Creating a document
Let’s try add document to the collection and then select it.
1 2 3 4 5 |
MongoCollection<Document> c = db.getCollection("client_info"); System.out.println("Items count in collection: " + c.count()); Document d = new Document("name", "TheCodeExample").append("url", "https://thecodeexamples.com/"); c.insertOne(d); System.out.println("first item from collection: " + c.find().first().toJson()); |
This is what will be displayed on the console
1 2 |
Items count in collection: 0 first item from collection: { "_id" : { "$oid" : "592553008bddb748214b9223" }, "name" : "TheCodeExample", "url" : "https://thecodeexamples.com/" } |
You can also select a document using filters
1 2 |
Document documentFromFilter = c.find(eq("name", "TheCodeExample")).first(); System.out.println("item from collection selected by filter: " + documentFromFilter.toJson()); |