MongoDB 作為主流文檔型數據庫,Java 驅動提供了豐富的 API。本文基於 mongo-java-driver 3.x/4.x,演示連接構建、條件查詢、排序分頁、游標轉 List、結果計數等核心操作,代碼開箱即用。
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.12.14</version> <!-- 或 4.x 版本 -->
</dependency>
import com.mongodb.*;
import com.mongodb.client.*;
import org.bson.Document;
import java.util.List;
public class MongoBasicDemo {
public static void main(String[] args) {
// 1. 建立連接 (單機模式)
MongoClient mongoClient = MongoClients.create("mongodb://127.0.0.1:27017");
// 2. 獲取數據庫與集合
MongoDatabase db = mongoClient.getDatabase("credit_2");
MongoCollection<Document> coll = db.getCollection("report");
// 3. 構建查詢條件
Document filter = new Document("user_id", "10065716153075");
// 多條件示例: new Document("user_id", "10065716153075").append("version", 3)
// 4. 執行查詢:排序 + 分頁
// -1 降序 (最新優先),1 升序
FindIterable<Document> iterable = coll.find(filter)
.sort(new Document("create_time", -1))
.limit(10); // 只取前 10 條
// 5. 轉為 List (一次性加載到內存,注意大數據量)
List<Document> list = iterable.into(new ArrayList<>());
System.out.println("返回文檔數: " + list.size());
// 6. 總計數 (不受 limit 影響)
long total = coll.countDocuments(filter);
System.out.println("符合條件總數: " + total);
// 7. 遍歷打印
for (Document doc : list) {
System.out.println(doc.toJson());
}
// 8. 關閉連接 (應用關閉時)
mongoClient.close();
}
}
| 操作 | 方法 | 說明 |
|---|---|---|
| 等值查詢 | new Document("field", value) | 自動匹配類型,"3" ≠ 3 |
| 範圍查詢 | new Document("age", new Document("$gte", 18)) | 使用 $gt/$gte/$lt/$lte/$ne/$in 等操作符 |
| 排序 | .sort(new Document("field", -1)) | 1 升序,-1 降序,可鏈式多字段 |
| 分頁 | .skip(offset).limit(pageSize) | skip 跳過前 N 條,limit 限制返回數 |
| 投影 | .projection(new Document("field", 1)) | 1 包含,0 排除,_id 默認包含需顯式排除 |
| 計數 | coll.countDocuments(filter) | 準確計數,替代已棄用的 count() |
| 游標轉 List | iterable.into(new ArrayList()) | 一次性加載,大數據集慎用 |
| 流式處理 | iterable.iterator() / .forEach() | 逐條處理,內存友好 |
CodecRegistry + PojoCodecProvider 直接映射實體類,避免手動 Document 轉換。user_id, create_time) 必須建立複合索引:coll.createIndex(Indexes.compoundIndex(Indexes.ascending("user_id"), Indexes.descending("create_time")))。MongoClientSettings 中的 maxConnectionPoolSize、minConnectionsPerHost 等參數。MongoClient.find().subscribe() 支援 Reactive Streams。new Document("_id", new ObjectId("hexString"))。skip 深分頁性能差,建議使用「游標分頁」: 記住上一頁最後一條的 _id/sortKey,下次查詢 {_id: {$gt: lastId}}。MongoClient 為線程安全單例,應用生命周期內僅創建一次,關閉時調用 close()。Java 操作 MongoDB 核心在於「構建 Document 過濾器 → 鏈式調用排序分頁 → 選擇加載方式」。掌握 BasicDBObject/Document 構建技巧、索引設計原則、連接池管理,即可高效完成絕大多數業務開發。建議新項目直接使用 4.x 驅動並配合 POJO 映射,代碼更類型安全、可維護性更強。