Java mongodb example for beginners

Carmen 95 Published: 09/28/2024

Java mongodb example for beginners

I'd be happy to help! However, please note that I'll respond in English as you've requested.

Now, let's dive into a step-by-step Java MongoDB example perfect for beginners!

Prerequisites:

Java 8 or higher: Ensure you have Java installed and configured on your system. Mongodb: Download and install Mongodb from the official website (https://www.mongodb.com/). Create a new database and collection for this tutorial.

Step-by-Step Example:

Step 1: Install MongoDB Driver for Java Download the MongoDB Java driver from here. Add the following Maven dependency to your project's pom.xml file (if you're using Maven) or install the JAR manually:

org.mongodb

mongo-java-driver

4.3.1

Step 2: Connect to MongoDB Create a new Java class (e.g., MongoDBExample.java) and add the following code:
import com.mongodb.MongoClient;

import com.mongodb.MongoCredential;

import com.mongodb.MongoDB;

import com.mongodb.ServerAddress;

public class MongoDBExample {

public static void main(String[] args) {

// Connect to MongoDB

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

MongoCredential.createCredential("your_database_name", "your_database_password").toArray());

// Get a reference to the database

MongoDB db = mongoClient.getDB("your_database_name");

}

}

Step 3: Create and Insert Documents In the MongoDBExample class, add the following code:
// Create a new collection (or use an existing one)

MongoDB collection = db.getCollection("mycollection");

// Create a new document

DBObject document = new BasicDBObject();

document.put("name", "John Doe");

document.put("age", 30);

// Insert the document into the collection

collection.insert(document);

Step 4: Query and Retrieve Documents In the MongoDBExample class, add the following code:
// Find all documents in the collection

BasicDBObject query = new BasicDBObject();

List results = collection.find(query).toArray();

// Print the results

for (BasicDBObject result : results) {

System.out.println(result);

}

Step 5: Close the MongoDB Connection In the MongoDBExample class, add the following code:
// Close the MongoDB connection

mongoClient.close();

Putting it all together:

Here's the complete code snippet for your reference:

import com.mongodb.BasicDBObject;

import com.mongodb.MongoClient;

import com.mongodb.MongoCredential;

import com.mongodb.MongoDB;

import com.mongodb.ServerAddress;

public class MongoDBExample {

public static void main(String[] args) {

// Connect to MongoDB

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

MongoCredential.createCredential("your_database_name", "your_database_password").toArray());

// Get a reference to the database

MongoDB db = mongoClient.getDB("your_database_name");

// Create and insert documents

MongoDB collection = db.getCollection("mycollection");

BasicDBObject document = new BasicDBObject();

document.put("name", "John Doe");

document.put("age", 30);

collection.insert(document);

// Query and retrieve documents

BasicDBObject query = new BasicDBObject();

List results = collection.find(query).toArray();

// Print the results

for (BasicDBObject result : results) {

System.out.println(result);

}

// Close the MongoDB connection

mongoClient.close();

}

}

This example demonstrates basic operations in MongoDB using Java:

Connecting to a MongoDB instance Creating and inserting documents into a collection Querying and retrieving documents from a collection

Feel free to modify the code as needed for your specific use case. Happy coding!

Java mongodb example github

I'm glad you asked!

If you're interested in using MongoDB with Java, there are several examples and tutorials available on GitHub that can help you get started.

Here are a few popular ones:

MongoDB Java Driver: This is an official MongoDB driver for Java, which provides a set of classes to interact with a MongoDB instance. You can find the source code and examples on GitHub: https://github.com/mongodb/mongo-java-driver.

Example code:

// Connecting to the database

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

// Getting a reference to the "mydatabase" database

DB db = client.getDB("mydatabase");

// Creating a new collection

DBCollection collection = db.getCollection("mycollection");

// Inserting data into the collection

DBObject document = new BasicDBObject("name", "John")

.append("age", 30)

.append("city", "New York");

collection.insert(document);

MongoDB Java Tutorial: This is a tutorial series on GitHub that covers the basics of using MongoDB with Java, including creating and managing databases, collections, documents, and queries: https://github.com/crazy-max/mongo-java-tutorial.

Example code:

// Creating a new MongoDB instance

MongoDB mongo = new MongoDB("localhost", 27017);

// Getting a reference to the "mydatabase" database

Database database = mongo.getDatabase("mydatabase");

// Creating a new collection

Collection collection = database.getCollection("mycollection");

// Inserting data into the collection

Document document = new Document("name", "John")

.append("age", 30)

.append("city", "New York");

collection.insertOne(document);

Java MongoDB CRUD Operations Example: This is an example project on GitHub that demonstrates basic CRUD (Create, Read, Update, Delete) operations with MongoDB using Java: https://github.com/rahulsagar/javadbexample.

Example code:

// Inserting data

public void insertDocument(String collectionName, String name, int age, String city) {

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

DB db = client.getDB("mydatabase");

DBCollection collection = db.getCollection(collectionName);

BasicDBObject document = new BasicDBObject()

.append("name", name)

.append("age", age)

.append("city", city);

collection.insert(document);

}

// Reading data

public List readDocuments(String collectionName, String query) {

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

DB db = client.getDB("mydatabase");

DBCollection collection = db.getCollection(collectionName);

BasicDBObject queryObject = new BasicDBObject();

queryObject.put(query, "John");

List documents = collection.find(queryObject).toList();

return documents;

}

// Updating data

public void updateDocument(String collectionName, String name, int newAge) {

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

DB db = client.getDB("mydatabase");

DBCollection collection = db.getCollection(collectionName);

BasicDBObject queryObject = new BasicDBObject();

queryObject.put("name", name);

BasicDBObject updateObject = new BasicDBObject();

updateObject.put("age", newAge);

collection.update(queryObject, updateObject);

}

// Deleting data

public void deleteDocument(String collectionName, String name) {

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

DB db = client.getDB("mydatabase");

DBCollection collection = db.getCollection(collectionName);

BasicDBObject queryObject = new BasicDBObject();

queryObject.put("name", name);

collection.remove(queryObject);

}

These examples should give you a good starting point for using MongoDB with Java. Happy coding!