Prerequisites
- MongoDB server installed and running.
- MongoDB Java driver added to your project.
Step-by-Step Guide
1. Set Up Dependencies
Ensure you have the MongoDB Java driver in your classpath. If you are using Maven, add the following dependency to your pom.xml
:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.4.1</version>
</dependency>
2. Establish a Database Connection
First, we need to establish a connection to the MongoDB database using the MongoClients
class.
3. Perform Basic CRUD Operations
We will perform Create, Read, Update, and Delete operations on a MongoDB collection.
Example Code
Below is the complete example code demonstrating how to connect to a MongoDB database and perform CRUD operations.
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import static com.mongodb.client.model.Filters.eq;
public class MongoDBExample {
private static final String CONNECTION_STRING = "mongodb://localhost:27017";
private static final String DATABASE_NAME = "testdb";
private static final String COLLECTION_NAME = "books";
public static void main(String[] args) {
// Establish a connection to MongoDB
try (MongoClient mongoClient = MongoClients.create(CONNECTION_STRING)) {
// Access the database
MongoDatabase database = mongoClient.getDatabase(DATABASE_NAME);
System.out.println("Connected to the database: " + DATABASE_NAME);
// Access the collection
MongoCollection<Document> collection = database.getCollection(COLLECTION_NAME);
System.out.println("Connected to the collection: " + COLLECTION_NAME);
// Perform CRUD operations
// Create
Document book1 = new Document("title", "Effective Java")
.append("author", "Joshua Bloch")
.append("year", 2008);
collection.insertOne(book1);
System.out.println("Inserted document: " + book1.toJson());
// Read
Document foundBook = collection.find(eq("title", "Effective Java")).first();
if (foundBook != null) {
System.out.println("Found document: " + foundBook.toJson());
} else {
System.out.println("Document not found");
}
// Update
collection.updateOne(eq("title", "Effective Java"),
new Document("$set", new Document("year", 2018)));
System.out.println("Updated document");
// Delete
collection.deleteOne(eq("title", "Effective Java"));
System.out.println("Deleted document");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Explanation
-
MongoDB Connection:
MongoClients.create(CONNECTION_STRING)
is used to establish a connection to the MongoDB server.- Replace
CONNECTION_STRING
with your actual MongoDB connection string.
-
Access the Database and Collection:
mongoClient.getDatabase(DATABASE_NAME)
accesses the database namedtestdb
.database.getCollection(COLLECTION_NAME)
accesses the collection namedbooks
.
-
CRUD Operations:
- Create: Insert a new document into the collection using
collection.insertOne()
. - Read: Retrieve a document from the collection using
collection.find().first()
. - Update: Update a document in the collection using
collection.updateOne()
. - Delete: Delete a document from the collection using
collection.deleteOne()
.
- Create: Insert a new document into the collection using
Output
Running the code will produce output similar to the following:
Connected to the database: testdb
Connected to the collection: books
Inserted document: {"title": "Effective Java", "author": "Joshua Bloch", "year": 2008}
Found document: {"title": "Effective Java", "author": "Joshua Bloch", "year": 2008}
Updated document
Deleted document
Conclusion
The MongoDB Java driver allows a Java application to connect to a MongoDB database. This tutorial demonstrated how to establish a connection and perform basic CRUD operations on a MongoDB collection. This approach can be adapted for more complex operations and use cases.
Comments
Post a Comment
Leave Comment