| 版本系列 | 特點 | 適用場景 |
|---|---|---|
| 2.x (Legacy) | 同步阻塞、API 簡單、已停止維護 | 舊項目維護、簡單工具類 |
| 3.x (Sync) | 同步阻塞、BSON 3.0、支援 MongoDB 4.0+ | 傳統 Spring MVC、批量任務 |
| 4.x (Sync/Async/Reactive) | 統一 API、支援事務、Change Streams、最新特性 | 新項目、Spring Boot 2.3+、高併發 |
本文基於 3.12.x 同步驅動演示,Maven 坐標:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.12.14</version>
</dependency>
// 單例模式管理 MongoClient(線程安全、連接池內置)
public class MongoManager {
private static final MongoClient CLIENT;
static {
// 生產建議:連接字符串含副本集、認證、SSL、壓縮
String uri = "mongodb://user:pass@host1:27017,host2:27017/db?replicaSet=rs0";
CLIENT = new MongoClient(new MongoClientURI(uri));
}
public static MongoClient getClient() { return CLIENT; }
public static void close() { CLIENT.close(); }
}
MongoCollection<Document> coll = db.getCollection("users");
// 單文檔
Document doc = new Document("name", "張三")
.append("age", 25)
.append("address", new Document("city", "北京").append("zip", "100000"));
coll.insertOne(doc);
// 批量插入 (有序/無序)
List<Document> docs = Arrays.asList(doc1, doc2, doc3);
coll.insertMany(docs, new InsertManyOptions().ordered(false)); // 無序寫入,單條失敗不影響其他
// 條件查詢
Document filter = new Document("age", new Document("$gte", 18))
.append("status", "active");
// 投影:只返回 name、age
Document projection = new Document("name", 1).append("age", 1).append("_id", 0);
// 排序 + 分頁
FindIterable<Document> iterable = coll.find(filter)
.projection(projection)
.sort(new Document("age", -1))
.skip(0).limit(20);
for (Document d : iterable) {
System.out.println(d.toJson());
}
// 計數 (3.x 用 countDocuments 替代已棄用 count)
long total = coll.countDocuments(filter);
// 單文檔更新:$set 修改指定字段
coll.updateOne(
Filters.eq("_id", id),
Updates.set("age", 26)
);
// 多文檔更新:$inc 原子增長
coll.updateMany(
Filters.eq("status", "active"),
Updates.inc("loginCount", 1)
);
// 替換整個文檔 (保留 _id)
coll.replaceOne(Filters.eq("_id", id), newDoc);
// 條件刪除
coll.deleteOne(Filters.eq("name", "張三"));
coll.deleteMany(Filters.lt("age", 18));
// 清空集合 (保留索引)
coll.drop(); // 刪除集合及索引
// coll.deleteMany(new Document()); // 僅清空數據
Filters.eq("address.city", "北京") (點號路徑)Updates.push("tags", "vip"), Updates.pull("tags", "expired"), Updates.addToSet("tags", "new") (去重)findOneAndUpdate 返回舊/新文檔,支援 ReturnDocument.AFTERcoll.createIndex(Indexes.ascending("name"));
coll.createIndex(Indexes.compoundIndex(
Indexes.ascending("status"), Indexes.descending("createTime")));
// TTL 索引自動清理過期數據
coll.createIndex(Indexes.ascending("expireAt"), new IndexOptions().expireAfter(0, TimeUnit.SECONDS));
try (ClientSession session = client.startSession()) {
session.startTransaction();
coll.insertOne(session, doc1);
coll.updateOne(session, filter, update);
session.commitTransaction();
} catch (Exception e) { session.abortTransaction(); }
| 維度 | 建議 |
|---|---|
| 連接池 | maxPoolSize=100、minPoolSize=10、maxIdleTimeMS=60000 |
| 讀寫關注 | ReadConcern.MAJORITY + WriteConcern.ACKNOWLEDGED (強一致) |
| 批量寫入 | insertMany(ordered=false) + 適當 batchSize |
| 投影裁剪 | 只選業務需要字段,減少網傳 |
| 索引覆蓋 | 查詢+排序+投影字段全在索引中,避免 FETCH |
MongoDB Java 驅動以 Document (BSON) 為核心載體,Filters/Updates/Indexes 靜態工廠方法構建類型安全的查詢/更新/索引定義。掌握 嵌套文檔點號路徑、數組原子操作、TTL 索引、事務會話 即可應對 95% 業務場景。新項目強烈建議升級 4.x 驅動並配合 Spring Data MongoDB 獲得 Repository 抽象與響應式支援。