MongoDB - Java
使用 Java 连接现代 MongoDB
Section titled “使用 Java 连接现代 MongoDB”本教程将引导您设置一个现代 Java 项目,以使用官方 MongoDB Java Driver 与 MongoDB 数据库进行交互。
使用构建工具设置项目
Section titled “使用构建工具设置项目”现代 Java 开发依赖于 Maven 或 Gradle 等构建工具来管理依赖。手动下载 JAR 文件是一种过时且容易出错的做法。您只需将 MongoDB Java Driver 依赖添加到项目的配置文件中。
Maven 依赖 (pom.xml)
Section titled “Maven 依赖 (pom.xml)”<dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> <version>4.11.1</version> <!-- 使用最新的稳定版本 --> </dependency> <!-- 强烈建议添加日志依赖 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>2.0.7</version> </dependency></dependencies>Gradle 依赖 (build.gradle.kts)
Section titled “Gradle 依赖 (build.gradle.kts)”dependencies { // 使用最新的稳定版本 implementation("org.mongodb:mongodb-driver-sync:4.11.1")
// 强烈建议添加日志依赖 implementation("org.slf4j:slf4j-simple:2.0.7")}连接到 MongoDB
Section titled “连接到 MongoDB”现代且推荐的连接方式是使用 MongoClients.create() 和连接字符串。这个单一字符串可以包含主机、端口、认证凭据以及其他连接选项。它既安全又灵活。
try-with-resources 语句确保在代码块退出时自动关闭 MongoClient 实例,从而正确释放所有数据库资源。
import com.mongodb.client.*;import org.bson.Document;
import static com.mongodb.client.model.Filters.eq;import static com.mongodb.client.model.Updates.set;
public class MongoCrudExample {
public static void main(String[] args) { // 替换为您的 MongoDB Atlas 连接字符串或本地实例 URI String uri = "mongodb://localhost:27017"; // 本地实例示例 // 对于 Atlas: "mongodb+srv://<username>:<password>@cluster.mongodb.net/?retryWrites=true&w=majority"
try (MongoClient mongoClient = MongoClients.create(uri)) { MongoDatabase database = mongoClient.getDatabase("myModernDb"); MongoCollection<Document> collection = database.getCollection("users");
System.out.println("Successfully connected to database: " + database.getName());
// 1. 清理之前的数据 collection.drop(); System.out.println("\n--- Dropped existing collection ---");
// 2. 创建/插入文档 Document newUser = new Document("name", "Ada Lovelace") .append("email", "ada@example.com") .append("country", "UK") .append("projects", 10); collection.insertOne(newUser); System.out.println("\n--- Inserted a document ---"); System.out.println(newUser.toJson());
// 3. 读取/查找文档 System.out.println("\n--- Reading the document ---"); Document foundUser = collection.find(eq("name", "Ada Lovelace")).first(); if (foundUser != null) { System.out.println("Found user: " + foundUser.toJson()); } else { System.out.println("User not found."); n}
// 4. 更新文档 collection.updateOne(eq("name", "Ada Lovelace"), set("projects", 12)); System.out.println("\n--- Updated the document ---"); Document updatedUser = collection.find(eq("name", "Ada Lovelace")).first(); System.out.println("User after update: " + updatedUser.toJson());
// 5. 删除文档 collection.deleteOne(eq("name", "Ada Lovelace")); System.out.println("\n--- Deleted the document ---"); long count = collection.countDocuments(); System.out.println("Documents in collection: " + count);
} catch (Exception e) { System.err.println("An error occurred: " + e.getMessage()); e.printStackTrace(); } }}Successfully connected to database: myModernDb
--- Dropped existing collection ---
--- Inserted a document ---{ "_id": { "$oid": "..." }, "name": "Ada Lovelace", "email": "ada@example.com", "country": "UK", "projects": 10 }
--- Reading the document ---Found user: { "_id": { "$oid": "..." }, "name": "Ada Lovelace", "email": "ada@example.com", "country": "UK", "projects": 10 }
--- Updated the document ---User after update: { "_id": { "$oid": "..." }, "name": "Ada Lovelace", "email": "ada@example.com", "country": "UK", "projects": 12 }
--- Deleted the document ---Documents in collection: 0关键现代化要点
Section titled “关键现代化要点”- 依赖管理:使用 Maven 或 Gradle,而不是手动 JAR 包。
- 连接:使用
MongoClients.create(uri)和连接字符串,以实现简洁性和安全性。 - 资源管理:使用
try-with-resources确保MongoClient始终正确关闭。 - CRUD 操作:使用现代、显式的方法,如
insertOne、updateOne、deleteOne、find和countDocuments。 - 错误处理:将数据库逻辑包装在
try-catch块中,以优雅地处理潜在异常。