首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 操作 MongoDB 入門:查詢、排序、分頁與 List 轉換實戰

     編輯:Java 相關知識

前言

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();
    }
}

關鍵 API 詳解

操作方法說明
等值查詢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()
游標轉 Listiterable.into(new ArrayList())一次性加載,大數據集慎用
流式處理iterable.iterator() / .forEach()逐條處理,內存友好

進階技巧

  1. POJO 映射:使用 CodecRegistry + PojoCodecProvider 直接映射實體類,避免手動 Document 轉換。
  2. 索引優化:高頻查詢字段 (如 user_id, create_time) 必須建立複合索引:coll.createIndex(Indexes.compoundIndex(Indexes.ascending("user_id"), Indexes.descending("create_time")))。
  3. 連接池配置:生產環境調整 MongoClientSettings 中的 maxConnectionPoolSize、minConnectionsPerHost 等參數。
  4. 異步操作:4.x 驅動提供 MongoClient.find().subscribe() 支援 Reactive Streams。

常見坑點

  • 類型敏感:MongoDB 嚴格區分 String/Int/Long/Double,查詢條件類型必須與存儲類型一致。
  • ObjectId 查詢:_id 為 ObjectId 時,需用 new Document("_id", new ObjectId("hexString"))。
  • 大數據量分頁:skip 深分頁性能差,建議使用「游標分頁」: 記住上一頁最後一條的 _id/sortKey,下次查詢 {_id: {$gt: lastId}}。
  • 資源洩漏:MongoClient 為線程安全單例,應用生命周期內僅創建一次,關閉時調用 close()。

總結

Java 操作 MongoDB 核心在於「構建 Document 過濾器 → 鏈式調用排序分頁 → 選擇加載方式」。掌握 BasicDBObject/Document 構建技巧、索引設計原則、連接池管理,即可高效完成絕大多數業務開發。建議新項目直接使用 4.x 驅動並配合 POJO 映射,代碼更類型安全、可維護性更強。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved