MongoDB Java example

Ophelia 84 Published: 12/16/2024

MongoDB Java example

I'm glad to respond in English for you!

Here's a comprehensive example of using MongoDB with Java:

Step 1: Installing the MongoDB Driver for Java

To start using MongoDB with your Java application, you need to install the MongoDB Java driver. You can do this by adding the following dependency to your pom.xml file (if you're using Maven) or your build.gradle file (if you're using Gradle):


org.mongodb

mongodb-driver-sync

4.3.1

dependencies {

implementation 'org.mongodb:mongodb-driver-sync:4.3.1'

}

Step 2: Connecting to the MongoDB Database

Next, you need to create a connection to your MongoDB database. You can do this by creating an instance of the MongoClient class:

import com.mongodb.MongoClient;

import com.mongodb.MongoCredential;

import com.mongodb.ServerAddress;

public class Main {

public static void main(String[] args) {

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

}

}

In this example, we're connecting to a local MongoDB instance running on port 27017. You can replace "localhost" and 27017 with your own database host name and port number.

Step 3: Creating the Database and Collection

Once you have connected to your MongoDB database, you need to create a database and collection where you want to store your data:

import com.mongodb.client.MongoDatabase;

import com.mongodb.client.MongoCollection;

public class Main {

public static void main(String[] args) {

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

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

MongoCollection collection = db.getCollection("mymusiccollection");

}

}

In this example, we're creating a database named mydatabase and a collection named mymusiccollection.

Step 4: Inserting Data

Now you can start inserting data into your MongoDB database. You can do this by using the insertOne() or insertMany() methods:

import com.mongodb.client.MongoCollection;

import com.mongodb.client.model.Bson;

public class Main {

public static void main(String[] args) {

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

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

MongoCollection collection = db.getCollection("mymusiccollection");

// Insert a document

Document document = new Document()

.append("title", "Song1")

.append("artist", "Artist1")

.append("genre", "Pop");

collection.insertOne(document);

// Insert multiple documents

List documents = new ArrayList<>();

for (int i = 0; i < 3; i++) {

Document document = new Document()

.append("title", "Song" + i)

.append("artist", "Artist" + i)

.append("genre", "Rock");

documents.add(document);

}

collection.insertMany(documents);

}

}

In this example, we're inserting a single document and multiple documents into our mymusiccollection.

Step 5: Querying Data

You can also query your MongoDB data using the find() or findAndModify() methods:

import com.mongodb.client.MongoCollection;

import com.mongodb.client.model.Bson;

public class Main {

public static void main(String[] args) {

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

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

MongoCollection collection = db.getCollection("mymusiccollection");

// Find all documents

FindIterable iterable = collection.find();

for (Document document : iterable) {

System.out.println(document.toJson());

}

// Find a specific document

Document query = new Document()

.append("genre", "Rock");

FindIterable iterable = collection.find(query);

for (Document document : iterable) {

System.out.println(document.toJson());

}

}

}

In this example, we're querying all documents in our mymusiccollection and then finding a specific document that has the genre "Rock".

Step 6: Updating Data

You can also update your MongoDB data using the updateOne() or updateMany() methods:

import com.mongodb.client.MongoCollection;

import com.mongodb.client.model.Bson;

public class Main {

public static void main(String[] args) {

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

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

MongoCollection collection = db.getCollection("mymusiccollection");

// Update a specific document

Document query = new Document()

.append("title", "Song1");

Updates updates = Updates.set("artist", "NewArtist1");

collection.updateOne(query, updates);

// Update multiple documents

List<UpdateOneModel> updateList = Arrays.asList(

new UpdateOneModel<>(new Document().append("title", "Song0"), Updates.set("genre", "Rock")),

new UpdateOneModel<>(new Document().append("title", "Song1"), Updates.set("genre", "Pop")),

new UpdateOneModel<>(new Document().append("title", "Song2"), Updates.set("genre", "Jazz"))

);

collection.updateMany(new BasicDBObject(), updates);

}

}

In this example, we're updating a specific document and then updating multiple documents.

Step 7: Deleting Data

Finally, you can delete your MongoDB data using the deleteOne() or deleteMany() methods:

import com.mongodb.client.MongoCollection;

import com.mongodb.client.model.Bson;

public class Main {

public static void main(String[] args) {

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

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

MongoCollection collection = db.getCollection("mymusiccollection");

// Delete a specific document

Document query = new Document()

.append("title", "Song1");

collection.deleteOne(query);

// Delete multiple documents

List<DeleteModel> deleteList = Arrays.asList(

new DeleteModel<>(new Document().append("title", "Song0")),

new DeleteModel<>(new Document().append("title", "Song2"))

);

collection.deleteMany(new BasicDBObject());

}

}

In this example, we're deleting a specific document and then deleting multiple documents.

That's it! This is a comprehensive guide to using MongoDB with Java. You can now start building your own MongoDB applications in Java!

How to read data from MongoDB in Java

I'll respond in English since you specifically asked for it. Here's a detailed guide on how to read data from MongoDB using Java:

Step 1: Install MongoDB and its Java Driver

To start, make sure you have MongoDB installed on your machine. You can download the Community Server edition from the official MongoDB website. Once installed, follow these steps to install the MongoDB Java driver (also known as MongoDB Java SDK):

Open a terminal or command prompt. Run the following command: mkdir -p ~/.m2/repository/com/mongodb (this will create a directory for storing the MongoDB Java driver). Navigate to that directory: cd ~/.m2/repository/com/mongodb Download the MongoDB Java driver using Maven by running this command: mvn dependency:get -Dartifact=org.mongodb:mongo-java-driver:1.18.0 (replace 1.18.0 with the desired version). Once the download is complete, navigate to your project directory and add the downloaded jar file to your project's classpath.

Step 2: Add MongoDB Java Driver Library

In your Java project, add the following dependency to your pom.xml (if you're using Maven) or your build.gradle file (if you're using Gradle):

Maven:


org.mongodb

mongo-java-driver

1.18.0

Gradle:

implementation 'org.mongodb:mongo-java-driver:1.18.0'

Step 3: Connect to MongoDB

Now that you have the Java driver installed and added as a dependency, it's time to connect to your MongoDB instance:

import com.mongodb.MongoClient;

import com.mongodb.MongoClientOptions;

import com.mongodb.MongoCredential;

import com.mongodb.ServerAddress;

public class ReadMongoData {

public static void main(String[] args) {

// Create a MongoClient instance with the desired connection settings

MongoCredential credential = MongoCredential.createCredential("your_database", "your_collection");

MongoClient mongoClient = new MongoClient(new ServerAddress("localhost"), credential);

// Use the MongoClient to read data from your MongoDB collection

}

}

Step 4: Read Data from MongoDB

To read data from a MongoDB collection, you'll need to use the getCollection() method on the MongoClient instance:

import com.mongodb.client.MongoCollection;

import com.mongodb.client.MongoDatabase;

public class ReadMongoData {

public static void main(String[] args) {

// Create a MongoClient instance with the desired connection settings

MongoCredential credential = MongoCredential.createCredential("your_database", "your_collection");

MongoClient mongoClient = new MongoClient(new ServerAddress("localhost"), credential);

// Get a reference to your MongoDB database

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

// Get a reference to your MongoDB collection

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

// Use the collection to read data from your MongoDB collection

FindIterable results = collection.find(new Document());

for (Document document : results) {

System.out.println(document);

}

}

}

In this example, we're using the find() method on the MongoCollection instance to query the documents in the "mycollection" collection. You can modify this code to suit your specific use case, such as filtering or projecting data.

That's it! With these steps, you should now be able to read data from a MongoDB collection using Java.