Vert.x MongoDB 客户端

这是一个 Vert.x 客户端,允许应用程序与 MongoDB 实例进行交互,无论是保存、检索、搜索还是删除文档。Mongo 非常适合在 Vert.x 应用程序中持久化数据,因为它原生支持 JSON (BSON) 文档。

特性

  • 完全非阻塞

  • 自定义编解码器,支持 Vert.x JSON 的快速序列化和反序列化

  • 支持 MongoDB Java 驱动程序的大部分配置选项

该客户端基于 MongoDB ReactiveStreams 驱动程序

使用 Vert.x MongoDB 客户端

要使用此项目,请将以下依赖项添加到您的构建描述符的依赖项部分

  • Maven(在您的 pom.xml 中)

<dependency>
  <groupId>io.vertx</groupId>
  <artifactId>vertx-mongo-client</artifactId>
  <version>5.0.1</version>
</dependency>
  • Gradle(在您的 build.gradle 文件中)

compile 'io.vertx:vertx-mongo-client:5.0.1'

创建客户端

您可以通过多种方式创建客户端

使用默认共享连接池

在大多数情况下,您会希望在不同的客户端实例之间共享一个连接池。

例如,您通过部署 Verticle 的多个实例来扩展应用程序,并且希望每个 Verticle 实例共享相同的连接池,这样就不会出现多个连接池。

最简单的方法如下:

MongoClient client = MongoClient.createShared(vertx, config);

首次调用 MongoClient.createShared 将实际创建连接池,并使用指定的配置。

后续调用将返回使用相同连接池的新客户端实例,因此配置不会被使用。

指定连接池源名称

您可以按如下方式创建指定连接池源名称的客户端:

MongoClient client = MongoClient.createShared(vertx, config, "MyPoolName");

如果使用相同的 Vert.x 实例并指定相同的连接池名称创建不同的客户端,它们将共享同一个连接池。

首次调用 MongoClient.createShared 将实际创建连接池,并使用指定的配置。

后续调用将返回使用相同连接池的新客户端实例,因此配置不会被使用。

如果您希望不同组的客户端拥有不同的连接池(例如,它们与不同的数据库进行交互),请使用这种创建方式。

创建一个非共享数据连接池的客户端

在大多数情况下,您会希望在不同的客户端实例之间共享一个连接池。但是,您可能希望创建一个不与任何其他客户端共享其连接池的客户端实例。

在这种情况下,您可以使用 MongoClient.create

MongoClient client = MongoClient.create(vertx, config);

这等同于每次调用 MongoClient.createShared 时都带上一个唯一的连接池名称。

使用 API

客户端 API 由 MongoClient 表示。

保存文档

要保存文档,请使用 save

如果文档没有 \_id 字段,则插入文档;否则,执行 upsert 操作。Upsert 表示如果文档不存在则插入,否则更新。

如果文档被插入且没有 id,则生成的 id 字段将返回给结果处理器。

以下是保存文档并获取其 ID 的示例:

JsonObject document = new JsonObject()
  .put("title", "The Hobbit");
mongoClient.save("books", document).onComplete(res -> {
  if (res.succeeded()) {
    String id = res.result();
    System.out.println("Saved book with id " + id);
  } else {
    res.cause().printStackTrace();
  }
});

以下是保存已包含 ID 的文档的示例。

JsonObject document = new JsonObject()
  .put("title", "The Hobbit")
  .put("_id", "123244");
mongoClient.save("books", document).onComplete(res -> {
  if (res.succeeded()) {
    // ...
  } else {
    res.cause().printStackTrace();
  }
});

插入文档

要插入文档,请使用 insert

如果文档被插入且没有 id,则生成的 id 字段将返回给结果处理器。

JsonObject document = new JsonObject()
  .put("title", "The Hobbit");
mongoClient.insert("books", document).onComplete(res -> {
  if (res.succeeded()) {
    String id = res.result();
    System.out.println("Inserted book with id " + id);
  } else {
    res.cause().printStackTrace();
  }
});

如果插入的文档带有 ID,并且已存在具有该 ID 的文档,则插入将失败

JsonObject document = new JsonObject()
  .put("title", "The Hobbit")
  .put("_id", "123244");
mongoClient.insert("books", document).onComplete(res -> {
  if (res.succeeded()) {
    //...
  } else {
    // Will fail if the book with that id already exists.
  }
});

更新文档

要更新文档,请使用 updateCollection

此方法更新集合中的一个或多个文档。作为 updateCollection 参数传入的 JSON 对象必须包含 更新操作符,并决定如何更新对象。

查询参数中指定的 JSON 对象决定了集合中哪些文档将被更新。

以下是更新 books 集合中文档的示例:

JsonObject query = new JsonObject()
  .put("title", "The Hobbit");
// Set the author field
JsonObject update = new JsonObject().put("$set", new JsonObject()
  .put("author", "J. R. R. Tolkien"));
mongoClient.updateCollection("books", query, update).onComplete(res -> {
  if (res.succeeded()) {
    System.out.println("Book updated !");
  } else {
    res.cause().printStackTrace();
  }
});

要指定更新是进行 upsert 还是更新多个文档,请使用 updateCollectionWithOptions 并传入 UpdateOptions 的实例。

它包含以下字段:

multi

设置为 true 以更新多个文档

upsert

如果查询不匹配,则设置为 true 以插入文档

writeConcern

此操作的写入关注

JsonObject query = new JsonObject()
  .put("title", "The Hobbit");
// Set the author field
JsonObject update = new JsonObject().put("$set", new JsonObject()
  .put("author", "J. R. R. Tolkien"));
UpdateOptions options = new UpdateOptions().setMulti(true);
mongoClient.updateCollectionWithOptions("books", query, update, options).onComplete(res -> {
  if (res.succeeded()) {
    System.out.println("Book updated !");
  } else {
    res.cause().printStackTrace();
  }
});

替换文档

要替换文档,请使用 replaceDocuments

这类似于更新操作,但它不接受任何操作符。相反,它用提供的文档替换整个文档。

以下是替换 books 集合中文档的示例:

JsonObject query = new JsonObject()
  .put("title", "The Hobbit");
JsonObject replace = new JsonObject()
  .put("title", "The Lord of the Rings")
  .put("author", "J. R. R. Tolkien");
mongoClient.replaceDocuments("books", query, replace).onComplete(res -> {
  if (res.succeeded()) {
    System.out.println("Book replaced !");
  } else {
    res.cause().printStackTrace();
  }
});

批量操作

要同时执行多个插入、更新、替换或删除操作,请使用 bulkWrite

您可以传递一个 BulkOperations 列表,其中每个操作都类似于匹配的单个操作。您可以根据需要传递任意数量的操作,甚至是相同类型的操作。

要指定批量操作是否按顺序执行以及使用何种写入选项,请使用 bulkWriteWithOptions 并传入 BulkWriteOptions 的实例。有关有序操作的更多解释,请参阅 操作执行

查找文档

要查找文档,请使用 find

query 参数用于匹配集合中的文档。

以下是一个简单的示例,使用空查询匹配所有书籍:

JsonObject query = new JsonObject();
mongoClient.find("books", query).onComplete(res -> {
  if (res.succeeded()) {
    for (JsonObject json : res.result()) {
      System.out.println(json.encodePrettily());
    }
  } else {
    res.cause().printStackTrace();
  }
});

以下是另一个匹配所有托尔金书籍的示例:

JsonObject query = new JsonObject()
  .put("author", "J. R. R. Tolkien");
mongoClient.find("books", query).onComplete(res -> {
  if (res.succeeded()) {
    for (JsonObject json : res.result()) {
      System.out.println(json.encodePrettily());
    }
  } else {
    res.cause().printStackTrace();
  }
});

匹配的文档将作为 JSON 对象列表返回给结果处理器。

要指定返回哪些字段、返回多少结果等,请使用 findWithOptions 并传入 FindOptions 的实例。

它包含以下字段:

fields(字段)

结果中要返回的字段。默认为 null,表示将返回所有字段。

sort(排序)

用于排序的字段。默认为 null

limit(限制)

返回结果的数量限制。默认为 -1,表示将返回所有结果。

skip(跳过)

在返回结果之前要跳过的文档数量。默认为 0

hint(提示)

要使用的索引。默认为空字符串。

批量查找文档

处理大型数据集时,不建议使用 findfindWithOptions 方法。为了避免将整个响应加载到内存中,请使用 findBatch

JsonObject query = new JsonObject()
  .put("author", "J. R. R. Tolkien");
mongoClient.findBatch("book", query)
  .exceptionHandler(throwable -> throwable.printStackTrace())
  .endHandler(v -> System.out.println("End of research"))
  .handler(doc -> System.out.println("Found doc: " + doc.encodePrettily()));

匹配的文档由 ReadStream 处理器逐个发出。

FindOptions 有一个额外的参数 batchSize,您可以使用它来设置一次加载的文档数量。

JsonObject query = new JsonObject()
  .put("author", "J. R. R. Tolkien");
FindOptions options = new FindOptions().setBatchSize(100);
mongoClient.findBatchWithOptions("book", query, options)
  .exceptionHandler(throwable -> throwable.printStackTrace())
  .endHandler(v -> System.out.println("End of research"))
  .handler(doc -> System.out.println("Found doc: " + doc.encodePrettily()));

默认情况下,batchSize 设置为 20。

查找单个文档

要查找单个文档,请使用 findOne

这与 find 的工作方式相同,但它只返回第一个匹配的文档。

删除文档

要删除文档,请使用 removeDocuments

query 参数用于匹配集合中的文档,以确定要删除哪些文档。

以下是删除所有托尔金书籍的示例:

JsonObject query = new JsonObject()
  .put("author", "J. R. R. Tolkien");
mongoClient.removeDocuments("books", query).onComplete(res -> {
  if (res.succeeded()) {
    System.out.println("Never much liked Tolkien stuff!");
  } else {
    res.cause().printStackTrace();
  }
});

删除单个文档

要删除单个文档,请使用 removeDocument

这与 removeDocuments 的工作方式相同,但它只删除第一个匹配的文档。

统计文档

要统计文档,请使用 count

以下是一个统计托尔金书籍数量的示例。该数量会传递给结果处理器。

JsonObject query = new JsonObject()
  .put("author", "J. R. R. Tolkien");
mongoClient.count("books", query).onComplete(res -> {
  if (res.succeeded()) {
    long num = res.result();
  } else {
    res.cause().printStackTrace();
  }
});

管理 MongoDB 集合

所有 MongoDB 文档都存储在集合中。

要获取所有集合的列表,可以使用 getCollections

mongoClient.getCollections().onComplete(res -> {
  if (res.succeeded()) {
    List<String> collections = res.result();
  } else {
    res.cause().printStackTrace();
  }
});

要创建一个新集合,可以使用 createCollection

mongoClient.createCollection("mynewcollectionr").onComplete(res -> {
  if (res.succeeded()) {
    // Created ok!
  } else {
    res.cause().printStackTrace();
  }
});

要删除一个集合,可以使用 dropCollection

删除集合将删除其中的所有文档!
mongoClient.dropCollection("mynewcollectionr").onComplete(res -> {
  if (res.succeeded()) {
    // Dropped ok!
  } else {
    res.cause().printStackTrace();
  }
});

运行其他 MongoDB 命令

您可以使用 runCommand 运行任意 MongoDB 命令。

命令可用于运行更高级的 MongoDB 功能,例如使用 MapReduce。有关支持的 命令 的更多信息,请参阅 MongoDB 文档。

以下是运行聚合命令的示例。请注意,命令名称必须作为参数指定,并且也必须包含在表示该命令的 JSON 中。这是因为 JSON 不是有序的,而 BSON 是有序的,MongoDB 要求第一个 BSON 条目是命令的名称。为了让我们知道 JSON 中的哪个条目是命令名称,它必须作为参数指定。

JsonObject command = new JsonObject()
  .put("aggregate", "collection_name")
  .put("pipeline", new JsonArray());
mongoClient.runCommand("aggregate", command).onComplete(res -> {
  if (res.succeeded()) {
    JsonArray resArr = res.result().getJsonArray("result");
    // etc
  } else {
    res.cause().printStackTrace();
  }
});

MongoDB 扩展 JSON 支持

目前,只支持 dateoidbinary 类型(参见 MongoDB 扩展 JSON)。

以下是插入带 date 字段文档的示例:

JsonObject document = new JsonObject()
  .put("title", "The Hobbit")
  //ISO-8601 date
  .put("publicationDate", new JsonObject().put("$date", "1937-09-21T00:00:00+00:00"));
mongoService.save("publishedBooks", document).compose(id -> {
  return mongoService.findOne("publishedBooks", new JsonObject().put("_id", id), null);
}).onComplete(res -> {
  if (res.succeeded()) {
    System.out.println("To retrieve ISO-8601 date : "
      + res.result().getJsonObject("publicationDate").getString("$date"));
  } else {
    res.cause().printStackTrace();
  }
});

以下是插入带有二进制字段的文档并将其读回的示例(Java 版):

byte[] binaryObject = new byte[40];
JsonObject document = new JsonObject()
  .put("name", "Alan Turing")
  .put("binaryStuff", new JsonObject().put("$binary", binaryObject));
mongoService.save("smartPeople", document).compose(id -> {
  return mongoService.findOne("smartPeople", new JsonObject().put("_id", id), null);
}).onComplete(res -> {
  if (res.succeeded()) {
    byte[] reconstitutedBinaryObject = res.result().getJsonObject("binaryStuff").getBinary("$binary");
    //This could now be de-serialized into an object in real life
  } else {
    res.cause().printStackTrace();
  }
});

以下是插入 Base64 编码字符串、将其类型设为二进制字段并将其读回的示例:

String base64EncodedString = "a2FpbHVhIGlzIHRoZSAjMSBiZWFjaCBpbiB0aGUgd29ybGQ=";
JsonObject document = new JsonObject()
  .put("name", "Alan Turing")
  .put("binaryStuff", new JsonObject().put("$binary", base64EncodedString));
mongoService.save("smartPeople", document).compose(id -> {
  return mongoService.findOne("smartPeople", new JsonObject().put("_id", id), null);
}).onComplete(res -> {
  if (res.succeeded()) {
    String reconstitutedBase64EncodedString = res.result().getJsonObject("binaryStuff").getString("$binary");
    //This could now converted back to bytes from the base 64 string
  } else {
    res.cause().printStackTrace();
  }
});

以下是插入对象 ID 并将其读回的示例:

String individualId = new ObjectId().toHexString();
JsonObject document = new JsonObject()
  .put("name", "Stephen Hawking")
  .put("individualId", new JsonObject().put("$oid", individualId));
mongoService.save("smartPeople", document).compose(id -> {
  JsonObject query = new JsonObject().put("_id", id);
  return mongoService.findOne("smartPeople", query, null);
}).onComplete(res -> {
  if (res.succeeded()) {
    String reconstitutedIndividualId = res.result().getJsonObject("individualId").getString("$oid");
  } else {
    res.cause().printStackTrace();
  }
});

获取去重值

以下是获取去重值的示例:

JsonObject document = new JsonObject()
  .put("title", "The Hobbit");
mongoClient.save("books", document).compose(v -> {
  return mongoClient.distinct("books", "title", String.class.getName());
}).onComplete(res -> {
  if (res.succeeded()) {
    System.out.println("Title is : " + res.result().getJsonArray(0));
  } else {
    res.cause().printStackTrace();
  }
});

以下是批量模式下获取去重值的示例:

JsonObject document = new JsonObject()
  .put("title", "The Hobbit");
mongoClient.save("books", document).onComplete(res -> {
  if (res.succeeded()) {
    mongoClient.distinctBatch("books", "title", String.class.getName())
      .handler(book -> System.out.println("Title is : " + book.getString("title")));
  } else {
    res.cause().printStackTrace();
  }
});
  • 以下是带查询条件获取去重值的示例:

JsonObject document = new JsonObject()
  .put("title", "The Hobbit")
  .put("publicationDate", new JsonObject().put("$date", "1937-09-21T00:00:00+00:00"));
JsonObject query = new JsonObject()
  .put("publicationDate",
    new JsonObject().put("$gte", new JsonObject().put("$date", "1937-09-21T00:00:00+00:00")));
mongoClient.save("books", document).compose(v -> {
  return mongoClient.distinctWithQuery("books", "title", String.class.getName(), query);
}).onComplete(res -> {
  if (res.succeeded()) {
    System.out.println("Title is : " + res.result().getJsonArray(0));
  }
});

以下是带查询条件在批量模式下获取去重值的示例:

JsonObject document = new JsonObject()
  .put("title", "The Hobbit")
  .put("publicationDate", new JsonObject().put("$date", "1937-09-21T00:00:00+00:00"));
JsonObject query = new JsonObject()
  .put("publicationDate", new JsonObject()
    .put("$gte", new JsonObject().put("$date", "1937-09-21T00:00:00+00:00")));
mongoClient.save("books", document).onComplete(res -> {
  if (res.succeeded()) {
    mongoClient.distinctBatchWithQuery("books", "title", String.class.getName(), query)
      .handler(book -> System.out.println("Title is : " + book.getString("title")));
  }
});

存储/检索文件和二进制数据

客户端可以使用 MongoDB GridFS 存储和检索文件以及二进制数据。MongoGridFsClient 可用于向 GridFS 上传或从 GridFS 下载文件和流。

获取 MongoGridFsClient 以与 GridFS 交互。

通过调用 createGridFsBucketService 并提供桶名称来创建 MongoGridFsClient。在 GridFS 中,桶名称最终会成为一个集合,其中包含对所有存储对象的引用。您可以通过提供唯一名称将对象分隔到不同的桶中。

它包含以下字段:

bucketName:要创建的桶的名称

以下是获取具有自定义桶名称的 MongoGridFsClient 的示例:

mongoClient.createGridFsBucketService("bakeke").onComplete(res -> {
  if (res.succeeded()) {
    //Interact with the GridFS client...
    MongoGridFsClient client = res.result();
  } else {
    res.cause().printStackTrace();
  }
});

GridFS 使用名为 "fs" 的默认桶。如果您更喜欢获取默认桶而不是自定义名称,请调用 createDefaultGridFsBucketService

以下是获取具有默认桶名称的 MongoGridFsClient 的示例。

mongoClient.createDefaultGridFsBucketService().onComplete(res -> {
  if (res.succeeded()) {
    //Interact with the GridFS client...
    MongoGridFsClient client = res.result();
  } else {
    res.cause().printStackTrace();
  }
});

从 GridFS 中删除整个文件桶。

整个文件桶及其所有内容都可以通过 drop 删除。它将删除创建 MongoGridFsClient 时指定的桶。

以下是删除文件桶的示例。

gridFsClient.drop().onComplete(res -> {
  if (res.succeeded()) {
    //The file bucket is dropped and all files in it, erased
  } else {
    res.cause().printStackTrace();
  }
});

查找 GridFS 桶中的所有文件 ID。

可以使用 findAllIds 找到桶中所有文件 ID 的列表。可以使用 downloadFileByID 通过 ID 下载文件。

以下是检索文件 ID 列表的示例。

gridFsClient.findAllIds().onComplete(res -> {
  if (res.succeeded()) {
    List<String> ids = res.result(); //List of file IDs
  } else {
    res.cause().printStackTrace();
  }
});

查找 GridFS 桶中与查询匹配的文件 ID。

可以指定查询来匹配 GridFS 桶中的文件。findIds 将返回与查询匹配的文件 ID 列表。

它包含以下字段:

query:这是一个 JSON 对象,可以使用标准 MongoDB 查询操作符匹配文件的任何元数据。一个空的 JSON 对象将匹配所有文档。您可以根据 GridFS 手册中描述的 GridFS 文件集合属性进行查询。https://docs.mongodb.com/manual/core/gridfs/#the-files-collection

文件可以通过 downloadFileByID 通过 ID 下载。

以下是根据元数据查询检索文件 ID 列表的示例。

JsonObject query = new JsonObject().put("metadata.nick_name", "Puhi the eel");
gridFsClient.findIds(query).onComplete(res -> {
  if (res.succeeded()) {
    List<String> ids = res.result(); //List of file IDs
  } else {
    res.cause().printStackTrace();
  }
});

根据 ID 删除 GridFS 中的文件。

以前存储在 GridFS 中的文件可以通过提供文件 ID 来使用 delete 删除。文件 ID 可以使用 findIds 通过查询检索。

它包含以下字段:id:GridFS 在存储文件时生成的 ID

以下是按 ID 删除文件的示例。

String id = "56660b074cedfd000570839c"; //The GridFS ID of the file
gridFsClient.delete(id).onComplete(res -> {
  if (res.succeeded()) {
    //File deleted
  } else {
    //Something went wrong
    res.cause().printStackTrace();
  }
});

在 GridFS 中上传文件

文件可以通过 uploadFile 按名称存储。成功后,将返回 GridFS 生成的 ID。此 ID 可用于以后检索文件。

它包含以下字段:

fileName:这是用于在 GridFS 中保存文件的名称

gridFsClient.uploadFile("file.name").onSuccess(id -> {
  //The ID of the stored object in Grid FS
});

在 GridFS 中上传带选项的文件。

文件可以使用 uploadFileWithOptions 并传入 GridFsUploadOptions 实例来存储额外的选项。成功后,将返回 GridFS 生成的 ID。

它包含以下字段:

metadata:这是一个 JSON 对象,包含在后续搜索中可能非常有用的任何元数据。chunkSizeBytes:GridFS 将按此大小将文件分成块。

以下是指定分块大小和元数据的 `uploadByFileName` 文件上传示例。

JsonObject metadata = new JsonObject();
metadata.put("nick_name", "Puhi the Eel");

GridFsUploadOptions options = new GridFsUploadOptions();
options.setChunkSizeBytes(1024);
options.setMetadata(metadata);

gridFsClient.uploadFileWithOptions("file.name", options).onSuccess(id -> {
  //The ID of the stored object in Grid FS
});

下载以前存储在 GridFS 中的文件

文件可以通过其原始名称使用 downloadFile 下载。下载完成后,结果处理器将以 Long 类型返回下载的长度。

它包含以下字段:

fileName(文件名)

之前存储的文件名

以下是使用在 GridFS 中存储的文件名下载文件的示例。

gridFsClient.downloadFile("file.name").onSuccess(fileLength -> {
});

根据 ID 下载之前存储在 GridFS 中的文件

文件可以通过其 ID 使用 downloadFileByID 下载到给定文件名。下载成功后,结果处理器将以 Long 类型返回下载的长度。

它包含以下字段:

id:GridFS 在存储文件时生成的 ID

以下是使用文件在 GridFS 中存储时获得的 ID 下载文件的示例。

String id = "56660b074cedfd000570839c";
String filename = "puhi.fil";
gridFsClient.downloadFileByID(id, filename).onSuccess(fileLength -> {
  //The length of the file stored in fileName
});

从 GridFS 下载文件并另存为新名称

文件可以使用其原始名称解析,然后通过 downloadFileAs 下载到新名称。下载成功后,结果处理器将以 Long 类型返回下载的长度。

它包含以下字段:

fileName:之前存储的文件名 newFileName:文件将存储的新名称

gridFsClient.downloadFileAs("file.name", "new_file.name").onComplete(fileLength -> {
  //The length of the file stored in fileName
});

上传流到 GridFS

流可以使用 uploadByFileName 上传到 GridFS。一旦流上传成功,结果处理器将被调用,并带回 GridFS 生成的 ID。

它包含以下字段:

stream:要上传的 ReadStream fileName:流将存储的名称

以下是将文件流上传到 GridFS 的示例

gridFsStreamClient.uploadByFileName(asyncFile, "kanaloa").onSuccess(id -> {
});

带选项将流上传到 GridFS

流可以使用 uploadByFileNameWithOptions 并传入 GridFsUploadOptions 实例来上传到 GridFS。一旦流上传成功,结果处理器将被调用,并带回 GridFS 生成的 ID。

它包含以下字段:

stream:要上传的 ReadStream fileName:流将存储的名称 options:上传选项

GridFsUploadOptions 包含以下字段:

metadata:这是一个 JSON 对象,包含在后续搜索中可能非常有用的任何元数据。chunkSizeBytes:GridFS 将按此大小将文件分成块。

以下是带选项将文件流上传到 GridFS 的示例:

GridFsUploadOptions options = new GridFsUploadOptions();
options.setChunkSizeBytes(2048);
options.setMetadata(new JsonObject().put("catagory", "Polynesian gods"));
gridFsStreamClient.uploadByFileNameWithOptions(asyncFile, "kanaloa", options).onSuccess(id -> {
});

使用文件名从 GridFS 下载流

流可以使用 downloadByFileName 使用文件名从 GridFS 下载。一旦流下载完成,结果处理器将被调用,并带回流的长度(Long 类型)。

它包含以下字段:

stream:要下载到的 WriteStream fileName:将下载到流中的文件名。

以下是将文件下载到流的示例

gridFsStreamClient.downloadByFileName(asyncFile, "kamapuaa.fil").onSuccess(length -> {
});

使用文件名从 GridFS 下载带选项的流

流可以使用 downloadByFileNameWithOptions 并传入 GridFsDownloadOptions 实例,使用文件名和下载选项从 GridFS 下载。一旦流下载完成,结果处理器将被调用,并带回流的长度(Long 类型)。

它包含以下字段:

stream:要下载到的 WriteStream fileName:将下载到流中的文件名 optionsGridFsDownloadOptions 的实例

DownloadOptions 包含以下字段:

revision:要下载的文件的版本

以下是带选项将文件下载到流的示例:

GridFsDownloadOptions options = new GridFsDownloadOptions();
options.setRevision(0);
gridFsStreamClient.downloadByFileNameWithOptions(asyncFile, "kamapuaa.fil", options).onSuccess(length -> {
});

使用 ID 从 GridFS 下载流

流可以使用 downloadById 使用 GridFS 生成的 ID 下载。一旦流下载完成,结果处理器将被调用,并带回流的长度(Long 类型)。

它包含以下字段:

stream:要下载到的 WriteStream id:GridFS 生成的 ID 的字符串表示形式

以下是使用对象 ID 将文件下载到流的示例:

String id = "58f61bf84cedfd000661af06";
gridFsStreamClient.downloadById(asyncFile, id).onSuccess(length -> {
});

配置客户端

客户端使用 JSON 对象进行配置。

Mongo 客户端支持以下配置:

db_name(数据库名称)

要使用的 MongoDB 实例中的数据库名称。默认为 default_db

useObjectId

启用此选项以支持将 ObjectId 作为字符串持久化和检索。如果设置为 true,十六进制字符串将作为原生 MongoDB ObjectId 类型保存到文档集合中。这将允许根据创建时间对文档进行排序。您还可以使用 ObjectId::getDate() 从十六进制字符串派生创建时间。对于您选择的其他类型,请设置为 false。如果设置为 false 或保持默认,则如果文档中省略了 _id,将生成十六进制字符串作为文档的 _id。默认为 false

Mongo 客户端尝试支持驱动程序允许的大多数选项。有两种方式配置 Mongo 供驱动程序使用:通过连接字符串或通过单独的配置选项。

connection_string(连接字符串)

驱动程序用于创建客户端的连接字符串。例如:mongodb://:27017。有关连接字符串格式的更多信息,请查阅驱动程序文档。

特定驱动程序配置选项

{
  // Single Cluster Settings
  "host" : "127.0.0.1", // string
  "port" : 27017,      // int

  // Multiple Cluster Settings
  "hosts" : [
    {
      "host" : "cluster1", // string
      "port" : 27000       // int
    },
    {
      "host" : "cluster2", // string
      "port" : 28000       // int
    },
    ...
  ],
  "replicaSet" :  "foo",    // string
  "serverSelectionTimeoutMS" : 30000, // long

  // Connection Pool Settings
  "maxPoolSize" : 50,                // int
  "minPoolSize" : 25,                // int
  "maxIdleTimeMS" : 300000,          // long
  "maxLifeTimeMS" : 3600000,         // long
  "waitQueueTimeoutMS" : 10000,      // long
  "maintenanceFrequencyMS" : 2000,   // long
  "maintenanceInitialDelayMS" : 500, // long

  // Credentials / Auth
  "username"   : "john",     // string
  "password"   : "passw0rd", // string
  "authSource" : "some.db"   // string
  // Auth mechanism
  "authMechanism"     : "GSSAPI",        // string
  "gssapiServiceName" : "myservicename", // string

  // Socket Settings
  "connectTimeoutMS" : 300000, // int
  "socketTimeoutMS"  : 100000, // int
  "sendBufferSize"    : 8192,  // int
  "receiveBufferSize" : 8192,  // int

  // Server Settings
  "heartbeatFrequencyMS"    : 1000, // long
  "minHeartbeatFrequencyMS" :  500, // long

  // SSL Settings
  "ssl" : false,                       // boolean
  "sslInvalidHostNameAllowed" : false, // boolean
  "trustAll" : false,                  // boolean
  "keyPath" : "key.pem",               // string
  "certPath" : "cert.pem",             // string
  "caPath" : "ca.pem",                 // string

  // Network compression Settings
  "compressors"           : ["zstd", "snappy", "zlib"],  // string array
  "zlibCompressionLevel"  : 6                            // int
}

驱动程序选项说明

host(主机)

MongoDB 实例运行的主机。默认为 127.0.0.1。如果指定了 hosts,则此项将被忽略。

port(端口)

MongoDB 实例监听的端口。默认为 27017。如果指定了 hosts,则此项将被忽略。

hosts(主机列表)

表示支持 MongoDB 集群(分片/副本集)的主机和端口的数组

host(主机)

集群中的一个主机

port(端口)

集群中主机监听的端口

replicaSet(副本集)

副本集的名称,如果 MongoDB 实例是副本集成员

serverSelectionTimeoutMS(服务器选择超时毫秒)

MongoDB 驱动程序在对操作选择服务器之前等待的最长时间(以毫秒为单位),超过此时间将引发错误。

maxPoolSize(最大连接池大小)

连接池中的最大连接数。默认值为 100

minPoolSize(最小连接池大小)

连接池中的最小连接数。默认值为 0

maxIdleTimeMS(最大空闲时间毫秒)

池化连接的最大空闲时间。默认值为 0,表示没有限制。

maxLifeTimeMS(最大生存时间毫秒)

池化连接的最长存活时间。默认值为 0,表示没有限制。

waitQueueTimeoutMS(等待队列超时毫秒)

线程等待连接变为可用的最长时间。默认值为 120000(2 分钟)。

maintenanceFrequencyMS(维护频率毫秒)

维护任务运行之间的时间间隔。默认值为 0

maintenanceInitialDelayMS(维护初始延迟毫秒)

在连接池上运行第一个维护任务之前等待的时间段。默认值为 0

username(用户名)

用于身份验证的用户名。默认为 null(表示不需要身份验证)。

password(密码)

用于身份验证的密码。

authSource(认证源)

与用户凭据关联的数据库名称。默认值为 db_name 的值。

authMechanism(认证机制)

要使用的认证机制。有关更多详细信息,请参阅[认证](http://docs.mongodb.org/manual/core/authentication/)。

gssapiServiceName

如果 authMechanism 指定为 GSSAPI,则为 Kerberos 服务名称。

connectTimeoutMS(连接超时毫秒)

尝试连接前超时的毫秒数。默认值为 10000(10 秒)。

socketTimeoutMS(套接字超时毫秒)

在尝试发送或接收套接字操作超时之前的毫秒数。默认值为 0,表示没有超时。

sendBufferSize(发送缓冲区大小)

设置套接字的发送缓冲区大小 (SO_SNDBUF)。默认值为 0,表示将使用操作系统的默认值。

receiveBufferSize(接收缓冲区大小)

设置套接字的接收缓冲区大小 (SO_RCVBUF)。默认值为 0,表示将使用操作系统的默认值。

heartbeatFrequencyMS(心跳频率毫秒)

集群监视器尝试连接每个服务器的频率。默认值为 5000(5 秒)。

minHeartbeatFrequencyMS(最小心跳频率毫秒)

最小心跳频率。默认值为 1000(1 秒)。

ssl

在 vertx-mongo-client 和 mongo 之间启用 SSL

sslInvalidHostNameAllowed

接受服务器证书中不包含的主机名

trustAll(信任所有)

使用 SSL 时,信任 所有 证书。警告 - 信任 所有 证书将使您面临潜在的安全问题,例如 MITM 攻击。

keyPath(密钥路径)

设置一个文件路径,该文件包含客户端密钥,在与 mongo 建立 SSL 连接时将用于对服务器进行身份验证。

certPath(证书路径)

设置一个文件路径,该文件包含证书,在与 mongo 建立 SSL 连接时将用于对服务器进行身份验证。

caPath(CA 路径)

设置一个文件路径,该文件包含一个证书,在与 mongo 建立 SSL 连接时将用作信任源。

compressors(压缩器)

设置网络传输的压缩算法。有效值范围为 [snappy, zlib, zstd],默认值为 null(表示不压缩)。

为了支持 snappyzstd 压缩算法,必须向您的项目构建描述符添加额外的依赖项(分别是 snappy-javazstd-java)。

zlibCompressionLevel(zlib 压缩级别)

设置 zlib 的压缩级别。有效值介于 -1 和 9 之间,如果启用 zlib,默认值为 -1。

上面列出的大多数默认值都使用 MongoDB Java 驱动程序的默认值。请查阅驱动程序文档以获取最新信息。