Updated February 27, 2023
Introduction to MongoDB Java Drivers
MongoDB is a NoSQL database that stores data in JSON type Documents and to access this data, using Java API, MongoDB Java Drivers are used. These drivers are used to perform CRUD (Create, Read, Update and Delete) operations over data in Collections, Current Version MongoDB Java Drivers is 4.0, released in April 2020, after 3.12. There were few changes made in 3.12 which have been carry forwarded with 4.0, without adding anything new. Changes like Improvements in Security, Automatic Encryption and Decryption for MongoDB Enterprise Advanced Users. It supports setting the BSON representation of java.util.UUID instance with a new UuidRepresentation tag on MongoClientSettings.
Features of MongoDB Java Drivers
SO basically, Java Drivers is the package that allows Java developers to interact with the MongoDB database. It provides a way to establish a synchronous and asynchronous connection with the database.
- To establish a connection to the Database using Programming Language API.
- Fetch and Send Statements and Documents to MongoDB.
- Insert and Retrieve the Documents from the Database.
Before moving ahead, we need to make sure we have MongoDB, Java Drivers for MongoDB, and Java.
MongoDB Java Drivers
Now that we have understood what MongoDB’s Java Drivers are and the basic features, let us begin with understanding these drivers along with proper examples and output:
Establishing a Connection MongoClient(): Now that we have understood what Java Drivers are, let us begin with making a connection with MongoDB with Java drivers. To connect with live MongoDB instance, we will create a new object of MongoClient().
MongoClient mongoClient = new MongoClient();
or
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
1. Authentication
We can establish a secure connection with the instance if in case the MongoDB is secured with a password. We have to pass credentials as parameters while attempting to establish a connection.
To Connect with a Database, we use:
MongoDatabase database = mongo.getDatabase("test");
Explanation: These parameters and methods are used to connect and secure a connection with live MongoDB instance. once we have written a java program with these lines of codes, save the file with .java extension, then compile the java file and execute the generated class file.
2. Listing the Collections
In order to check and list all the collections available in the mongodb database, we use getCollectionNames(). Following is the syntax for getCollectionNames():
Set<String> collection = db.getCollectionNames();
It is also possible to list down all collections with listCollectionNames(). This listCollectionNames() method is part of com.mongodb.client.MongoDatabase class. Syntax for listCollectionNames():
for (String colname : database.listCollectionNames()) {
System.out.println(colname);
}
3. Get Collection
Now that we have listed every collection present in the database, using getCollection() we can specifically select on the collection and work on it. Following is the syntax:
DBCollection collection = db.getCollection("collection");
4. Creating a Collection
Now that we have established a connection let’s move ahead with creating a createCollection() method. This method, createCollecton() is part of the com.MongoDB.client.MongoDatabase class.
"database.createCollection("test");"
5. Drop a Collection
Like creating a collection, it is essential to understand how to delete or drop a collection properly. Here we will use the drop() method, which belongs to com.mongodb.client.MongoCollection class as well.
MongoCollection<Document> collection = database.getCollection("test");
collection.drop();
Explanation: The above code will delete the collection named test.
6. Inserting a Document
We, now have established a secure connection, listed all the collections present in the database, and selected one collection, so let’s insert a single document.
document.put(“Name”,”Sulaksh”);
document.put(“City”,”Pune”);
collectionname.insertOne(document);
Explanation: In the above syntax, insertOne passes a simple parameter, which holds all the details that are to be inserted in the collection as a new document. And just like insertOne, insertMany can also be used to in case of bulk documents.
7. Delete a Document
The above method explains how to delete a single collection, now let us delete a document, from a collection. We will use the deleteOne() method, which is part of the same class as the drop method. Basically, we have two ways to delete, either use deleteOn method or deleteMany method, depending on the need. Let us learn both, syntax for deleteOne():
collectionname.deleteOne(Filters.eq("city", "Pune"));
Explanation: This syntax will search for a document that matches with the filter and delete the first document.
deleteMany(): Deletes all documents that match with the given filter, in the collection. In case if no document matches, there will be no deletion. The syntax is as follows:
collectionname.deleteMany(Filters.eq("city", "Pune"));
Explanation: Above is a proper syntax, which will search and delete every record in the collection which has Pune has its City.
8. Update a Document
Out of the CRUD operations, we learned about creating, deleting, reading the documents, so let us now understand the working of update method as in Java Drivers. Like delete, we have two ways to work with the update: updateOne () and updateMany(). Here, we will use the collectionname.update() method. The syntax is as follow:
collectionname.updateOne(searchQuery, updateQuery );
Explanation: In the above syntax, searchQuery is the find command which will allow us to locate the document which we want to update, and later updateQuery will allow us to update that located query to make amendments as our need. This will only work with a single document.
updateMany(): Let us now understand updateMany(), which is used to make the changes needed in a collection on multiple documents. The syntax is as follows:
collectionname.updateMany(searchQuery, updateQuery );
Explanation: Same as for updateOne, searchQuery is the criteria for selecting the documents that are to be updated. At the same time, updateQuery holds the values that are to be modified with. Upon execution, these queries will return the result of the operation. Based on the method used and the parameters passed, the result will be modified.
Conclusion
To conclude, MongoDB Java Drivers allow Java Programmers to interact with the Database on API level. We understood the definitions and syntaxes as required to execute CRUD operations. To Run and Execute a MongoDB Java Driver Code, we need Live and Running Instance of MongoDB, Installed and Configured MongoDB Driver. Java Drivers makes it easy for Java Developers to work with MongoDB.
Recommended Articles
This is a guide to MongoDB Java Drivers. Here we discuss an introduction to MongoDB Java Drivers and the features, drivers, explanation and examples. You can also go through our other related articles to learn more –