EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials MongoDB Tutorial MongoDB Java Drivers
Secondary Sidebar
MongoDB Tutorial
  • Advanced
    • MongoDB Array
    • PostgreSQL ARRAY_AGG()
    • Indexes in MongoDB
    • MongoDB create Index
    • MongoDB Collection
    • MongoDB List Collections
    • MongoDB Capped Collections
    • MongoDB Delete Collection
    • Mongodb show collections
    • MongoDB Auto Increment
    • MongoDB Triggers
    • MongoDB Projection
    • Replication in MongoDB
    • MongoDB Database
    • Mongo DB Create Database
    • MongoDB Compass
    • MongoDB Users
    • MongoDB Authentication
    • MongoDB GridFS
    • MongoDB Relationships
    • MongoDB MapReduce
    • MongoDB Geospatial
    • MongoDB Monitoring
    • Backup in MongoDB
    • MongoDB Sharding
    • MongoDB Java Drivers
    • MongoDB Import
    • Mongo Database Interview Questions
    • MongoDB Join Two Collections
    • MongoDB Group by Multiple Fields
    • MongoDB Pagination
    • MongoDB Replica Set
    • MongoDB Bulk Update
    • MongoDB greater than
    • MongoDB Encryption
    • MongoDB find in array
    • MongoDB like query
    • Mongodb shell
    • MongoDB port
    • MongoDB Query Operators
    • MongoDB Web Interface
    • MongoDB Query Array
    • MongoDB Transactions
    • MongoDB Not In
    • MongoDB not null
    • MongoDB npm
    • MongoDB Remove
  • Basics
    • What is MongoDB
    • How To Install MongoDB
    • MongoDB Tools
    • MongoDB GUI Tools
    • MongoDB Versions
    • MongoDB Commands
    • Advantages of MongoDB
    • MongoDB Features
    • Is MongoDB NoSQL
    • Is MongoDB Open Source
    • Build Web Applications using MongoDB
    • MongoDB Data Types
    • MongoDB Administration
    • Data Modeling in MongoDB
    • MongoDB vs Elasticsearch
    • MariaDB vs MongoDB
    • Firebase vs MongoDB
  • Commands
    • Mongodb updateMany
    • MongoDB Aggregation
    • Mongodb unwind
    • Mongodb where
    • MongoDB BSON
    • MongoDB Filter
    • Mongodb Match
    • MongoDB sort by date
    • MongoDB Limit()
    • MongoDB Atlas Login
    • MongoDB Relational Database
    • MongoDB count
    • MongoDB Aggregate
    • MongoDB Distinct
    • MongoDB Unique
    • MongoDB find
    • MongoDB findOne()
    • MongoDB insert
    • MongoDB Delete
    • MongoDB Update
    • Lookup in MongoDB
    • order by in MongoDB
    • MongoDB $regex
    • MongoDB $elemMatch
    • MongoDB ObjectId()
    • MongoDB Skip()
    • MongoDB findAndModify
    • Mongodb findOneAndUpdate
    • MongoDB Date Query
    • MongoDB Timestamp
    • MongoDB sort()
    • MongoDB group by
    • MongoDB Join

Related Courses

MongoDB Certification Course

Oracle Certification Course

All in One Data Science Course

SQL Training Course

Oracle DBA Course

MS SQL Certification Course

MongoDB Java Drivers

By Sulaksh MoreSulaksh More

MongoDB Java Drivers

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.

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,768 ratings)

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.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

  • 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 –

  1. What is MongoDB?
  2. MongoDB vs SQL server
  3. MongoDB Collection
  4. Lookup in MongoDB
Popular Course in this category
MongoDB Training Program (4 Courses, 2 Projects)
  4 Online Courses |  2 Hands-on Projects |  22+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Oracle Training (14 Courses, 8+ Projects)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
SQL Training Program (7 Courses, 8+ Projects)4.7
Oracle DBA Database Management System Training (2 Courses)4.7
MS SQL Training (16 Courses, 11+ Projects)4.7
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more