Default Image

Months format

Show More Text

Load More

Related Posts Widget

Article Navigation

Contact Us Form

404

Sorry, the page you were looking for in this blog does not exist. Back Home

How to Connect to MongoDB Via MongoDB Java Driver?

MongoDB is a NoSQL cross-platform document-oriented database and is one of the most popular databases available written in C++. 10gen released MongoDB as an open-source project in February 2009.

Java and MongoDB are two of the most well-known technologies for software development. So, their working together will not be a surprising moment at all.


MongoDB



Whether you're developing on a local or on-premises MongoDB installation or going cloud-first with MongoDB Atlas, the MongoDB Java Driver and encompassing environment make it a snap to incorporate MongoDB into your development process.

Some salient features of MongoDB

MongoDB, commonly known as just "Mongo" is actually a NoSQL document-based database. It is primarily used to store and organize data without using a relational table or columnar configuration.

  • It stores information or data in JSON-like documents, which can vary in their structural forms.
  • It generally uses dynamic schemas, and that implies that we can make records without predefining anything.
  • The whole structure or shape of the record can be altered either by adding new fields or deleting any older ones.


Hence, this data model enables you in order to represent hierarchical relationships, store arrays, and other more intricate structures by easy modes.

How to connect to MongoDB with Java Driver

In order to determine how to connect or interact MongoDB with Java and explore the basic CRUD (Create, Retrieve, Update, and Delete) operations, here is a particular software, namely Java Driver. That is assumed as the most renowned and highly recommended MongoDB driver app, most precisely for the Java Language.

Assuming you are using an alternate or a different programming language. For this, you would have to use the particular driver for that language you opt for as you own. MongoDB gives official drivers to the most generally utilized programming languages.

The driver reveals certain APIs, which ensures working with the database is easier. Moreover, it simplifies the connection or interaction between the business logic and data stored in your apps.

Get to know MongoDB Java Driver by an example.

Let's fabricate some example snippets in order to demonstrate CRUD operations in a Java application through the Java driver. But prior to diving into writing the code to manipulate data, let's first add the MongoDB Java driver dependency to your project.

Also Read - IFvod

I'm going to use Maven to build the project here. So let's add the following dependency in the `pom.xml` file, which could be found in the project's root directory:

 

 

 

 <dependency>

       <groupId>org.mongodb</groupId>

       <artifactId>mongodb-driver-sync</artifactId>

       <version>3.4.0</version>

   </dependency>

 

 

 

Now, It is an all-in-one JAR, which embeds the core driver and BSON. BSON, short for Bin­ary JSON, is a bin­ary-en­coded seri­al­iz­a­tion of JSON-like doc­u­ments. In order to consolidate the database connection and its related logic and expose some strategies for our application to consume:

 

import com.mongodb.client.MongoClients;

import com.mongodb.client.MongoDatabase;

 

import java.util.logging.Level;

import java.util.logging.Logger;

 

public class MongoListCollections {

 

    public static void main(String[] args) {

 

        Logger mongoLogger = Logger.getLogger("org.mongodb.driver");

        mongoLogger.setLevel(Level.SEVERE);

 

        try (var mongoClient = MongoClients.create("mongodb://localhost:27017")) {

 

            MongoDatabase database = mongoClient.getDatabase("testdb");

 

            for (String name : database.listCollectionNames()) {

 

                System.out.println(name);

            }

        }

    }

}

 



After compiling and running this project, you will see the list of database names that are printed on the console by indicating the driver integration and the database connection works as expected. Thus, you will figure out that I have set up the driver effectively and successfully.

Now, let's put a glance over some ways to read and write data from our application.

Create a database with a collection

In this part, you will be figuring out how to perform CRUP (Create Read Update Delete) operation from our application code on a MongoDB database.
Insert A Document

You can modify the main class as follows to insert a single document:

 

 

import com.mongodb.client.MongoClients;

import org.bson.Document;

 

import java.util.Map;

 

public class MongoCommand {

 

    public static void main(String[] args) {

 

        try (var mongoClient = MongoClients.create("mongodb://localhost:27017")) {

 

            var database = mongoClient.getDatabase("testdb");

 

            var stats = database.runCommand(new Document("dbstats", 1));

 

            for (Map.Entry<String, Object> set : stats.entrySet()) {

 

                System.out.format("%s: %s%n", set.getKey(), set.getValue());

            }

        }

    }

}

 

 After compiling and running this code, a new document will be inserted into the menu collection of the database.


Read Document

The easiest way to query data from MongoDB is to find everything in a collection. This is assumed as the default behavior of the find method when no arguments are passed to it.

 

 

import com.mongodb.client.MongoClients;

import com.mongodb.client.MongoCollection;

import com.mongodb.client.MongoCursor;

import org.bson.Document;

 

import java.util.ArrayList;

 

public class MongoReadAll {

 

    public static void main(String[] args) {

 

        try (var mongoClient = MongoClients.create("mongodb://localhost:27017")) {

 

            var database = mongoClient.getDatabase("testdb");

 

            MongoCollection<Document> collection = database.getCollection("cars");

 

            try (MongoCursor<Document> cur = collection.find().iterator()) {

 

                while (cur.hasNext()) {

 

                    var doc = cur.next();

                    var cars = new ArrayList<>(doc.values());

 

                    System.out.printf("%s: %s%n", cars.get(1), cars.get(2));

                }

            }

        }

    }

}

 

 

Update Documents

For updating a single document, you could use the "updateOne" method and update multiple documents by the "updateMany" method. You can modify one or more than one field in the documents by an update operation.

A code snippet for a single document update by given as follows:

 

import com.mongodb.BasicDBObject;

import com.mongodb.client.MongoClients;

import com.mongodb.client.MongoCollection;

import org.bson.Document;

import org.bson.types.ObjectId;

 

public class MongoCollectionFromJSON {

 

    public static void main(String[] args) {

 

        try (var mongoClient = MongoClients.create("mongodb://localhost:27017")) {

 

            var database = mongoClient.getDatabase("testdb");

 

            MongoCollection<Document> collection = database.getCollection("continents");

 

            var africa = BasicDBObject.parse("{_id : '" + ObjectId.get() + "', name : 'Africa'}");

            var asia = BasicDBObject.parse("{_id : '" + ObjectId.get() + "', name : 'Asia'}");

            var europe = BasicDBObject.parse("{_id : '" + ObjectId.get() + "', name : 'Europe'}");

            var america = BasicDBObject.parse("{_id : '" + ObjectId.get() + "', name : 'America'}");

            var australia = BasicDBObject.parse("{_id : '" + ObjectId.get() + "', name : 'Australia'}");

            var antarctica = BasicDBObject.parse("{_id : '" + ObjectId.get() + "', name : 'Antarctica'}");

 

            collection.insertOne(new Document(africa));

            collection.insertOne(new Document(asia));

            collection.insertOne(new Document(europe));

            collection.insertOne(new Document(america));

            collection.insertOne(new Document(australia));

            collection.insertOne(new Document(antarctica));

        }

    }

}

 

 

Delete Documents

Like other operations, it's possible to delete one or more documents via appropriate methods exposed to the driver. Now, let's look at a snippet to delete a single document from the collection:

 

 

 

import com.mongodb.MongoClient;

import com.mongodb.client.MongoCollection;

import org.bson.Document;

 

import static com.mongodb.client.model.Filters.eq;

 

public class MongoModify {

 

    public static void main(String[] args) {

 

        try (var mongoClient = new MongoClient("localhost", 27017)) {

 

            var database = mongoClient.getDatabase("testdb");

 

            MongoCollection<Document> collection = database.getCollection("cars");

 

            collection.deleteOne(eq("name", "Skoda"));

            collection.updateOne(new Document("name", "Audi"),

                    new Document("$set", new Document("price", 52000)));

 

        }

    }

}

 



Conclusion

From top to bottom, you have come to know about how to connect MongoDB with MongoDB Java Driver in the form of a codebase. In the meanwhile, the strategies to perform the fundamental operations of creating, retrieving, updating, and deleting documents from a collection. Moreover, you also determined how to programmatically create databases and collections using the APIs revealed through the driver. The Java driver for Mongo is feature-packed with cutting-edge capabilities such as aggregation. If you are keen on advancing your profundities about it, the official documentation can be an ideal spot to initiate.

Author Bio: 

Steve Parker has extensive experience with inbound marketing for various industries like eCom, Mfg, Real-estate, Education, and advertising. Having worked with a Digital Marketing Agency, he has gained expertise in digital content creation, SME acquisition, and white hat linking.

No comments:

Post a Comment