MongoDB Java Driver


  本文使用 Java 來描述對 Mongodb 的相關操作,數據庫版本是 3.2.8,驅動版本為 3.2.2。

  本文將討論

  • 如何連接MongoDB
  • 文檔的 CURD 操作
  • 文檔的上傳和下載
1. 連接到MongoDB

  首先保證 mongodb 啟動了身份驗證功能(不啟動直接使用IP,Port連接即可)。連接目標可分為三種:單機,集群和副本集。

1.1 連接單機和集群

  站在代碼的角度,單機和集群的區別就是端口號不同,假設服務器地址和端口號為:192.168.0.8和27017,則連接代碼如下:

String user = "admin";
String pwd = "111111";
String authDb = "admin";
String host = "192.168.0.8";
int port = 27017;
// 1. 直接連接
MongoCredential credential = MongoCredential.createCredential(user, authDb, pwd.toCharArray());
MongoClient mongoClient = new MongoClient(new ServerAddress(host , port), Arrays.asList(credential));

// 2. 使用連接字符串連接
// mongodb://user:pwd@host:port/?authSource=db
String conString = "mongodb://{0}:{1}@{2}:{3}/?authSource={4}";
MongoClientURI uri = new MongoClientURI(MessageFormat.format(conString, user, pwd, host, port+"", authDb)); //注意port為字符串
MongoClient mongoClient = new MongoClient(uri);
1.2 連接副本集
// 1. 直接連接
MongoClient mongoCli1ent = new MongoClient(
		  Arrays.asList(new ServerAddress("localhost", 27017),
		                new ServerAddress("localhost", 27018)),
		  Arrays.asList(MongoCredential.createCredential(user, authDb, pwd.toCharArray())));

// 2. 使用連接字符串
// mongodb://user:pwd@host:port, host:port/?authSource=db&replicaSet=rs&slaveOk=true
String conStr = "mongodb://{0}:{1}@{2}:{3},{4}:{5}/?authSource={6}&replicaSet={7}&slaveOk=true";
MongoClientURI uri=new MongoClientURI(MessageFormat.format(conStr,"admin","111","host1","27017","host2","27018","admin","rs0"));
MongoClient mongoClient = new MongoClient(uri);
1.3 關於連接相關的參數

  不管是使用字符串連接,還是直接連接都可以附帶一些參數,直接連接時用 MongoClientOptions 類的builder()構造,字符串直接使用 & 拼接在后面就行。常用的參數如下:

replicaSet=name 副本集名稱 ssl=true|false 是否使用ssl
connectTimeoutMS=ms 連接超時時間 socketTimeoutMS=ms socket超時時間
maxPoolSize=n 連接池大小 safe=true|false 驅動是否發送getLastError
journal=true|false 是否等待將日志刷到磁盤    
authMechanism= 身份驗證方式 驗證方式有SCRAM-SHA-1 MONGODB-X509,MONGO-CR,etc
authSource=string 驗證數據庫,默認admin 采用指定數據庫的驗證方式 3.0之后,默認驗證方式為 SCRAM-SHA-1.

更多詳細的參數請見:MongoClientURI

2. 文檔的 CURD 操作

  在進行 CURD 操作時,有幾個常用的輔助靜態類:Filters, Sorts, Projections,Updates,詳細用法請查看:Builders

(1)文檔的插入

// 獲取待插入集合 mycol
MongoDatabase mydb = mongoClient.getDatabase("myDb");
MongoCollection<Document> mycol =  mydb.getCollection("myCol");
// 生成一個文檔
Document doc = new Document();
doc.put("name", "cyhe");
doc.put("blog", "http://www.cnblogs.com/cyhe/");
// 也可以使用鏈式風格構建
new Document("id",1).append("name", "cyhe");// ... etc
// 也可以直接將 JSON 轉成 BSON
doc = Document.parse("{\"name\":\"cyhe\",\"blog\":\"http://www.cnblogs.com/cyhe/\"}");
// 插入
mycol.insertOne(doc);
// 批量插入
mycol.insertMany(new ArrayList<Document>());

(2)文檔的查找

// 查詢集合所有文檔
List<Document> docs = mycol.find().into(new ArrayList<Document>());
// 直接導入 import static com.mongodb.client.model.Filters.*; 就可以直接使用 and eq 等靜態方法		
// 查詢 age = 20 的文檔
Document doc = mycol.find(Filters.eq("age", 20)).first();
// 查詢 10<age<20 的文檔 返回一個游標
MongoCursor<Document> cur=mycol.find(Filters.and(Filters.gt("age", 10), Filters.lt("age", 20))).iterator();

(3)文檔的更新和刪除

// 查找並刪除名稱為 cyhe 的文檔
mycol.findOneAndDelete(Filters.eq("name", "cyhe"));
// 查找並重命名
mycol.findOneAndUpdate(Filters.eq("name", "cyhe"), Updates.set("name", "wqq"));
// 小於10的都加1
mycol.updateMany(Filters.lt("size", 10), Updates.inc("size", 1));
// 刪除 age 大於 110 的文檔
mycol.deleteOne(Filters.gt("age", "110"));

3. 文檔的上傳和下載

  在Mongodb中,普通文檔最大為16M,對於圖片,附件來說就顯得比較小了,mongodb的處理方式就是使用 GridFS 分塊存儲。

// GridFS 默認的名字為 fs,使用默認名稱連接
GridFSBucket gridFSBucket = GridFSBuckets.create(mydb);
// 使用指定名稱連接
GridFSBucket gridFSBucket1 = GridFSBuckets.create(mydb, "imags");
// 上傳文件
// ==============================================================================================
InputStream streamToUploadFrom = new FileInputStream(new File("/tmp/mongodb-tutorial.pdf"));
// 自定義參數
GridFSUploadOptions options = new GridFSUploadOptions()
                                    .chunkSizeBytes(1024)
                                    .metadata(new Document("type", "presentation"));
ObjectId fileId = gridFSBucket.uploadFromStream("mongodb-tutorial", streamToUploadFrom, options);
// ===============================================================================================
// 或者使用 GridFSUploadStream
byte[] data = "Data to upload into GridFS".getBytes(StandardCharsets.UTF_8);
GridFSUploadStream uploadStream = gridFSBucket.openUploadStream("sampleData", options);
uploadStream.write(data);
uploadStream.close();
System.out.println("The fileId of the uploaded file is: " + uploadStream.getFileId().toHexString());
// ===============================================================================================
// 下載文件
// ===============================================================================================
// 根據生成的 ObjectId 下載
FileOutputStream streamToDownloadTo = new FileOutputStream("/tmp/mongodb-tutorial.pdf");
gridFSBucket.downloadToStream(fileId, streamToDownloadTo);
streamToDownloadTo.close();
System.out.println(streamToDownloadTo.toString());
// ===============================================================================================
// 根據文件名稱下載
FileOutputStream streamToDownloadTo = new FileOutputStream("/tmp/mongodb-tutorial.pdf");
GridFSDownloadByNameOptions downloadOptions = new GridFSDownloadByNameOptions().revision(0);
gridFSBucket.downloadToStreamByName("mongodb-tutorial", streamToDownloadTo, downloadOptions);
streamToDownloadTo.close();
// ===============================================================================================
// 使用 GridFSDownloadStream 根據 ObjectId 下載
GridFSDownloadStream downloadStream = gridFSBucket.openDownloadStream(fileId);
int fileLength = (int) downloadStream.getGridFSFile().getLength();
byte[] bytesToWriteTo = new byte[fileLength];
downloadStream.read(bytesToWriteTo);
downloadStream.close();
System.out.println(new String(bytesToWriteTo, StandardCharsets.UTF_8));
// ===============================================================================================
// 使用 GridFSDownloadStream 根據 名稱 下載
GridFSDownloadStream downloadStream = gridFSBucket.openDownloadStreamByName("sampleData");
int fileLength = (int) downloadStream.getGridFSFile().getLength();
byte[] bytesToWriteTo = new byte[fileLength];
downloadStream.read(bytesToWriteTo);
downloadStream.close();
System.out.println(new String(bytesToWriteTo, StandardCharsets.UTF_8));

  本文只是 Mongodb 操作的冰山一角,更多的用法,會在以后的實戰中不斷更新完善。更多用法和 API 介紹,詳見 MongoDB-Java-3.2


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM