Working with MongoDb from java

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.

Let’s start working with the database.

1. Establishing a connection

First we create a connection to MongoDB

MongoClient can also be created simply by specifying the port and host separately

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.

3. Working with collections

After creating the MongoDatabase instance, use the getCollection() method to work with collections.

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.

This is what will be displayed on the console

You can also select a document using filters

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.