MongoDB Java Driver:MongoCore Driver 对比 MongoDB Driver 对比 MongoDB 异步 Driver

MongoDB Java Driver: MongoCore Driver vs. MongoDB Driver vs. MongoDB Async Driver

MongoDB Java driver:

有三个不同的 driver 选项
  1. 核心Driver
  2. MongoDB Driver
  3. MongoDB 异步 Driver

drivers description page 对它们中的每一个都进行了简要描述,但没有提供关于何时应该使用它们的进一步解释。我的问题:请你澄清一下使用它们的情况是什么?我什么时候应该选择一个而不是第二个,什么时候我 must/have 使用特定的 driver 选项?

TL;DR:

如果操作缓慢,请使用异步 driver,或者在大多数情况下使用常规 driver。你不应该使用核心 driver.

MongoDB 常规 Driver:

常规 driver 可用于搜索、创建、阅读、更新和删除文档。只要未返回结果或未完成操作(同步行为),find(...)updateMany(...)deleteMany(...) 和类似方法就会挂起。这是大多数程序使用的 driver,在大多数情况下都很好。

下面是插入单个文档的示例:

collection.insertOne(doc);
//Do something here.
System.out.println("Inserted!")

MongoDB 异步 Driver:

可用于搜索、创建、阅读、更新和删除文档的另一种 driver。此 driver 提供与常规 driver(find(...)updateMany(...)deleteMany(...) 等)类似的方法。

与常规driver的区别在于主线程不会挂起,因为异步driver在callback中发送结果(异步行为)。 driver 当操作需要很长时间(需要处理大量数据、高延迟、查询未索引字段等)并且您不想管理多个线程时使用。

插入单个文档时的回调示例如下:

collection.insertOne(doc, new SingleResultCallback<Void>() {
    @Override
    public void onResult(final Void result, final Throwable t) {
        //Do something here.
        System.out.println("Inserted!");
    }
});
// Do something to show that the Document was not inserted yet.
System.out.println("Inserting...")

有关详细信息,请阅读 this

MongoDB核心Driver

常规和异步 driver 的基础层。它包含 low-level 方法来执行常规和异步 driver 常见的所有操作。除非你正在为 MongoDB 制作一个新的 API / Driver,否则你不应该使用核心 driver.