How to query MongoDB using Java?

Sue 116 Published: 09/02/2024

How to query MongoDB using Java?

Querying MongoDB using Java involves the use of a MongoDB driver for Java. One popular and widely-used driver is the official MongoDB Java Driver, which provides a simple and intuitive way to interact with your MongoDB database.

Here are the basic steps to get started:

Install the MongoDB Java Driver: You can do this by adding the following dependency to your Maven or Gradle project:

org.mongodb

mongo-java-driver

4.3.1

Import the necessary classes: Once you have the driver installed, you'll need to import the necessary classes in your Java program:
import com.mongodb.BasicDBObject;

import com.mongodb.MongoClient;

import com.mongodb.client.FindIterable;

import com.mongodb.client.MongoCollection;

import com.mongodb.client.MongoDatabase;

Establish a connection: Create an instance of MongoClient and use it to connect to your MongoDB server:
MongoClient mongoClient = new MongoClient("localhost", 27017);

Get a reference to the collection you want to query: Use the MongoClient to get a reference to the MongoCollection that corresponds to the database and collection you want to query:
MongoDatabase db = mongoClient.getDatabase("mydatabase");

MongoCollection collection = db.getCollection("mycollection", DBObject.class);

Create a query document: Create a MongoDB query document using the BasicDBObject class. This is used to specify the criteria for your query:
BasicDBObject queryDocument = new BasicDBObject();

queryDocument.put("name", "John");

queryDocument.put("age", 30);

Find the matching documents: Use the find method on the MongoCollection to execute the query and retrieve a cursor over the matching documents:
FindIterable result = collection.find(queryDocument);

Process the results: Iterate over the results and process them as needed:
for (DBObject document : result) {

String name = (String) document.get("name");

int age = (int) document.get("age");

System.out.println("Found a matching document: name=" + name + ", age=" + age);

}

Here is the complete example code:

import com.mongodb.BasicDBObject;

import com.mongodb.MongoClient;

import com.mongodb.client.FindIterable;

import com.mongodb.client.MongoCollection;

import com.mongodb.client.MongoDatabase;

public class MongoDBQueryExample {

public static void main(String[] args) {

// Establish a connection

MongoClient mongoClient = new MongoClient("localhost", 27017);

// Get a reference to the collection you want to query

MongoDatabase db = mongoClient.getDatabase("mydatabase");

MongoCollection collection = db.getCollection("mycollection", DBObject.class);

// Create a query document

BasicDBObject queryDocument = new BasicDBObject();

queryDocument.put("name", "John");

queryDocument.put("age", 30);

// Find the matching documents

FindIterable result = collection.find(queryDocument);

// Process the results

for (DBObject document : result) {

String name = (String) document.get("name");

int age = (int) document.get("age");

System.out.println("Found a matching document: name=" + name + ", age=" + age);

}

}

}

This code demonstrates the basic steps for querying MongoDB using Java, including connecting to the database, creating a query document, finding the matching documents, and processing the results.

What are the dependencies for Java for MongoDB?

Java developers can interact with MongoDB using various drivers that provide a connection between their Java application and the NoSQL database. The dependencies required to work with MongoDB from Java include:

MongoDB Java Driver: This is the official driver developed by MongoDB, which provides a low-level API for interacting with the database. It is available as a Maven or Gradle dependency.

Dependency: com.mongodb:mongo-java-driver:3.12.7

Jackson Library: Jackson is a popular JSON processing library in Java that provides efficient and easy-to-use APIs for converting data structures to JSON and back. The MongoDB Java Driver uses Jackson under the hood, so you need to include it as well.

Dependency: com.fasterxml.jackson.core:jackson-databind:2.12.3

Apache Commons Lang: This library provides additional utility classes that are useful when working with text data.

Dependency: org.apache.commons:commons-lang3:3.12.0

SLF4J (Simple Logging Faced Interface for Java): SLF4J is a logging facade that allows you to use any logging framework (e.g., Logback, Log4j) with your application.

Dependency: org.slf4j:slf4j-api:1.7.32

Logback (or Log4j): This library handles the actual logging, providing log messages to a file or console.

Dependency: ch.qos.logback:logback-classic:1.2.3 (for Logback)

Dependency: log4j:log4j:1.2.17 (for Log4j)

To include these dependencies in your Maven project, you can add the following entries to your pom.xml file:


com.mongodb

mongo-java-driver

3.12.7

com.fasterxml.jackson.core

jackson-databind

2.12.3

org.apache.commons

commons-lang3

3.12.0

org.slf4j

slf4j-api

1.7.32

ch.qos.logback

logback-classic

1.2.3

log4j

log4j

1.2.17

For Gradle projects, you need to add the following dependencies in your build.gradle file:

dependencies {

implementation 'com.mongodb:mongo-java-driver:3.12.7'

implementation 'com.fasterxml.jackson.core:jackson-databind:2.12.3'

implementation 'org.apache.commons:commons-lang3:3.12.0'

implementation 'org.slf4j:slf4j-api:1.7.32'

// Optional: Use Logback or Log4j

implementation 'ch.qos.logback:logback-classic:1.2.3'

// Alternative for log4j instead of logback

implementation 'log4j:log4j:1.2.17'

}

Once you've included the necessary dependencies, you can use the MongoDB Java Driver to connect to your MongoDB database and perform CRUD (Create, Read, Update, Delete) operations.