![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to connect to a MongoDB database using a JDBC program?
MongoDB is a cross-platform, document oriented database that provides, high performance, high availability, and easy scalability. MongoDB works on concept of collection and document.
Before you start connecting MongoDB in you need to make sure that you have MongoDB JDBC driver. If not, download the jar from the path Download mongo.jar and, add it to your classpath.
Example
Following JDBC program establishes connection with the MongoDB database and creates a collection in it.
import com.mongodb.client.MongoDatabase; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; public class CreatingCollection { public static void main( String args[] ) { // Creating a Mongo client MongoClient mongo = new MongoClient( "localhost" , 27017 ); // Creating Credentials MongoCredential credential; credential = MongoCredential.createCredential("sampleUser", "myDb", "password".toCharArray()); System.out.println("Connected to the database successfully"); //Accessing the database MongoDatabase database = mongo.getDatabase("myDb"); //Creating a collection database.createCollection("sampleCollection"); System.out.println("Collection created successfully"); } }
Output
Connected to the database successfully Collection created successfully
Advertisements