Categories: Java

Java connectivity to MongoDB database

MongoDB is a no-SQL database that is document-oriented. MongoDB, which was first released in 2009, successfully replaced rows and columns in traditional relational data models with documents.

We do not need to use the JDBC API to connect to MongoDB because its API is completely independent and does not require any other external library.

Prerequisites:
  • A federated database instance that is associated with one or more data stores.
  • An application or BI tool that you want to connect to your federated database instance with the JDBC driver.
  • The JDBC driver for MongoDB.
Connectivity steps for Java application to MongoDB database:
  • Create MongoDB Instance
  • Access a Database
  • Access a Collection
  • Create a Document
  • Insert a Document
  • Fetch A Document
Create MongoDB Instance:

The MongoClient class connects to a MongoDB server and performs database-related operations. Here are a couple of examples:

MongoClient mongoClient = new MongoClient();

Connecting to a named MongoDB server listening on the default port (27017):

MongoClient mongoClient = new MongoClient("localhost");

Connecting to a named MongoDB server listening on a specific port:

MongoClient mongoClient = new MongoClient("localhost", 27017);
Access a Database:

After you’ve established a connection, you can use the getDatabase() method to retrieve a database by name.

for instance,

MongoDatabase db = mongoClient.getDatabase()("test");
Access a Collection:

Obtaining collections is a necessary step in querying and manipulating data. The getCollection() allows you to retrieve a collection by name.

MongoCollection<Document> collection = database.getCollection("testCollection");
Create & insert a Document:

Use the Document class and its append() method to add additional fields and values to the document object when creating the document with the Java driver.

example:

BasicDBObject doc = new BasicDBObject("name", "MongoDB").
                              append("type", "database").
                              append("count", 1).
                              append("info", new BasicDBObject("x", 203).append("y", 102));

After creating a document, we can add it to the collection. We can also insert single or multiple documents. The insertOne() method of the collection is used to insert a single document into it.

For example:

coll.insert(doc);
Fetch A Document:

The find() method can be used to retrieve a single document from a collection.

Simple example:

import com.mongodb.MongoClient;  
import com.mongodb.client.MongoCollection;  
import com.mongodb.client.MongoDatabase;  
import org.bson.Document;  
public class Demo {  
 public static void main(String[] args){  
  try{  
   // Connecting To MongoDB  
   MongoClient mongoClient = new MongoClient( "localhost" , 27017 );  
   // Creating DataBase   
   MongoDatabase db = mongoClient.getDatabase("test");  
   // Creating Collection/Table  
   MongoCollection<Document> table = database.getCollection("testCollection");  
   // Creating Document/Record    
   BasicDBObject doc = new BasicDBObject("name", "MongoDB").
                              append("type", "database").
                              append("count", 1).
                              append("info", new BasicDBObject("x", 203).append("y", 102));
  
   // Inserting Data  
   table.insertOne(doc);  
  }catch(Exception e){  
   System.out.println(e);  
  }  
 }  
}  
 

Note: also read about the Java connect to MySQL database with JDBC

Follow Me

If you like my post, please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

2 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago