核心特性
- 線程安全,單例
MongoClient 即可
- 內置連接池 (默認 100,可配)
完整示例代碼 (MongoDB 3.0+ API)
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.*;
import org.bson.Document;
import java.util.*;
public class MongoZyh {
public static void main(String[] args) {
try {
// 1. 構建連接 (含認證)
ServerAddress addr = new ServerAddress("localhost", 27017);
MongoCredential cred = MongoCredential.createScramSha1Credential("zyh", "admin", "zyh".toCharArray());
MongoClient client = new MongoClient(Arrays.asList(addr), Arrays.asList(cred));
// 2. 獲取庫/集合
MongoDatabase db = client.getDatabase("zyhdb");
MongoCollection coll = db.getCollection("student");
// 3. 插入單條
Document doc = new Document("name", "zhangsan").append("age", 28);
coll.insertOne(doc);
// 4. 批量插入
List docs = Arrays.asList(
new Document("name", "lisi").append("age", 28).append("sex", "男"),
new Document("name", "wangwu").append("age", 31).append("sex", "男")
);
coll.insertMany(docs);
// 5. 查詢全部
for (Document d : coll.find()) System.out.println(d);
// 6. 條件+正則+排序查詢
Document query = new Document("age", new Document("$lt", 30))
.append("sex", "男")
.append("name", Pattern.compile("^zhang"));
Document sort = new Document("name", -1);
for (Document d : coll.find(query).sort(sort)) {
System.out.printf("name:%s age:%s sex:%s%n", d.get("name"), d.get("age"), d.get("sex"));
}
// 7. 更新單條/多條
coll.updateOne(new Document("age", 28), new Document("$set", new Document("name", "zhangsan2")));
coll.updateMany(new Document("sex", "男"), new Document("$inc", new Document("age", 1)));
// 8. 刪除單條/多條
coll.deleteOne(new Document("age", 29));
coll.deleteMany(new Document("sex", "女"));
// 9. 刪除集合
// coll.drop();
} catch (Exception e) { e.printStackTrace(); }
}
}
關鍵 API 對照表
| 操作 | 單條方法 | 多條方法 |
| 插入 | insertOne() | insertMany() |
| 查詢 | find().first() | find() 返回 FindIterable |
| 更新 | updateOne() | updateMany() |
| 刪除 | deleteOne() | deleteMany() |
| 查詢並更新/刪除/替換 | findOneAndUpdate/Delete/Replace() | - |