杰瑞科技汇

Java如何连接MongoDB数据库?

Java连接MongoDB数据库

基本步骤

  1. 添加MongoDB Java驱动依赖
  2. 创建MongoClient实例
  3. 获取数据库和集合
  4. 执行CRUD操作
  5. 关闭连接

添加依赖

Maven项目

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver-sync</artifactId>
    <version>4.11.0</version> <!-- 使用最新版本 -->
</dependency>

Gradle项目

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

连接示例代码

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
public class MongoDBConnection {
    public static void main(String[] args) {
        // 1. 创建MongoClient连接
        String connectionString = "mongodb://localhost:27017";
        try (MongoClient mongoClient = MongoClients.create(connectionString)) {
            // 2. 获取数据库
            MongoDatabase database = mongoClient.getDatabase("testDB");
            // 3. 获取集合
            MongoCollection<Document> collection = database.getCollection("testCollection");
            // 4. 插入文档示例
            Document document = new Document("name", "John Doe")
                    .append("age", 30)
                    .append("email", "john@example.com");
            collection.insertOne(document);
            System.out.println("文档插入成功");
            // 5. 查询文档示例
            Document query = new Document("name", "John Doe");
            for (Document doc : collection.find(query)) {
                System.out.println(doc.toJson());
            }
        } catch (Exception e) {
            System.err.println("连接MongoDB时出错: " + e.getMessage());
        }
    }
}

连接选项

连接字符串格式

mongodb://[username:password@]host1[:port1][,host2[:port2],...]/[database][?options]

常见连接选项

// 带认证的连接
String connectionString = "mongodb://user:password@localhost:27017/?authSource=admin";
// 连接副本集
String connectionString = "mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=myReplicaSet";
// 连接选项
ConnectionString connString = new ConnectionString("mongodb://localhost:27017/?maxPoolSize=50");
MongoClient mongoClient = MongoClients.create(connString);

CRUD操作示例

插入文档

// 插入单个文档
Document doc = new Document("name", "Alice")
                .append("age", 25)
                .append("city", "New York");
collection.insertOne(doc);
// 插入多个文档
List<Document> documents = Arrays.asList(
    new Document("name", "Bob").append("age", 30),
    new Document("name", "Charlie").append("age", 35)
);
collection.insertMany(documents);

查询文档

// 查询所有文档
for (Document document : collection.find()) {
    System.out.println(document.toJson());
}
// 条件查询
Document query = new Document("age", new Document("$gt", 25));
for (Document document : collection.find(query)) {
    System.out.println(document.toJson());
}
// 投影查询
Document projection = new Document("name", 1).append("_id", 0);
for (Document document : collection.find().projection(projection)) {
    System.out.println(document.toJson());
}

更新文档

// 更新单个文档
Document query = new Document("name", "Alice");
Document update = new Document("$set", new Document("age", 26));
collection.updateOne(query, update);
// 更新多个文档
Document query = new Document("age", new Document("$lt", 30));
Document update = new Document("$inc", new Document("age", 1));
collection.updateMany(query, update);

删除文档

// 删除单个文档
Document query = new Document("name", "Alice");
collection.deleteOne(query);
// 删除多个文档
Document query = new Document("age", new Document("$gt", 40));
collection.deleteMany(query);

使用POJO类

如果需要将文档映射到Java对象,可以使用POJO支持:

Java如何连接MongoDB数据库?-图1
(图片来源网络,侵删)
// 1. 添加依赖
<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver-sync</artifactId>
    <version>4.11.0</version>
</dependency>
// 2. 定义POJO类
public class Person {
    private String name;
    private int age;
    // getters and setters
}
// 3. 配置编解码器
CodecRegistry pojoCodecRegistry = fromRegistries(
    MongoClientSettings.getDefaultCodecRegistry(),
    fromProviders(PojoCodecProvider.builder().automatic(true).build())
);
// 4. 使用POJO
MongoCollection<Person> collection = database
    .getCollection("people", Person.class)
    .withCodecRegistry(pojoCodecRegistry);
Person person = new Person("Jane Doe", 28);
collection.insertOne(person);

注意事项

  1. 确保MongoDB服务已启动
  2. 检查防火墙设置,确保端口可访问
  3. 生产环境中应考虑连接池配置
  4. 使用try-with-resources确保连接关闭
  5. 对于大量数据操作,考虑使用批量操作提高性能

是Java连接MongoDB的基本方法和常用操作示例。

分享:
扫描分享到社交APP
上一篇
下一篇