- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Articles
- How to connect to Derby database using a JDBC program?
- How to connect to HSQLDB database using a JDBC program?
- How to connect to PostgreSQL database using a JDBC program?
- How to connect to an SQLite database using a JDBC program?
- How to insert Timestamp value in a database using JDBC program?
- How to drop a database using JDBC API?
- How to create a database in MySQL using a JDBC API?
- How to create a table in a database using JDBC API?
- How to drop a table from a database using JDBC API?
- How to create a function in a database using JDBC API?
- How to create a Stored procedure in a database using JDBC API?
- How to get all table names from a database using JDBC?
- How to drop a table from Oracle database using JDBC API?
- How to insert/store JSON array into a database using JDBC?
- How to connect Database in Python?

Advertisements