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

Java MongoDB CRUD 實戰:驅動版本選型、文檔操作、嵌套文檔與索引優化

     編輯:Java 相關知識

驅動版本選型指南

版本系列特點適用場景
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(); }
}

CRUD 核心操作

Create - 插入文檔

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)); // 無序寫入,單條失敗不影響其他

Read - 查詢與投影

// 條件查詢
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);

Update - 更新操作

// 單文檔更新:$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);

Delete - 刪除操作

// 條件刪除
coll.deleteOne(Filters.eq("name", "張三"));
coll.deleteMany(Filters.lt("age", 18));

// 清空集合 (保留索引)
coll.drop(); // 刪除集合及索引
// coll.deleteMany(new Document()); // 僅清空數據

進階實戰技巧

  1. 嵌套文檔查詢:Filters.eq("address.city", "北京") (點號路徑)
  2. 數組操作:Updates.push("tags", "vip"), Updates.pull("tags", "expired"), Updates.addToSet("tags", "new") (去重)
  3. 原子操作:findOneAndUpdate 返回舊/新文檔,支援 ReturnDocument.AFTER
  4. 索引創建:
    coll.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));
  5. 事務 (MongoDB 4.0+ 副本集):
    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 抽象與響應式支援。

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