问题
There are three different driver options for the MongoDB Java driver:
- Core Driver
- MongoDB Driver
- MongoDB Async Driver
The drivers description page gives a brief description of each of them but no further explanation is provided regarding when I should use each of them. My question: can you, please, clarify what are the cases to use each of them? When should I prefer one over the second and when I must/have to use the particular driver option?
回答1:
TL;DR:
Use the async driver if the operations are slow, or use the regular driver in most cases. You shouldn't use the core driver.
MongoDB Regular Driver:
General driver that you can use to search, create, read, update and delete documents. The find(...)
, updateMany(...)
, deleteMany(...)
and similar methods will hang for as long as the result is not returned or the operation not done (synchronous behavior). This is the driver that most program uses and is good in most cases.
Here is an example for inserting a single Document:
collection.insertOne(doc);
//Do something here.
System.out.println("Inserted!")
MongoDB Async Driver:
Another type of driver that you can use to search, create, read, update and delete documents. This driver offers similar methods than the regular driver (find(...)
, updateMany(...)
, deleteMany(...)
, etc.).
The difference with the regular driver is that the main thread will not hang because the async driver sends the result in a callback (asynchronous behavior). This driver is used when the operations can take a long time (a lot of data to go through, high latency, query on unindexed fields, etc.) and you do not want to manage multiple threads.
Here is an example of the callback when inserting a single Document:
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...")
For more informations, read this.
MongoDB Core Driver
Base layer of the regular and async drivers. It contains low-level methods to do all the operations common to the regular and async drivers. Unless you are making a new API / Driver for MongoDB, you shouldn't use the core driver.
来源:https://stackoverflow.com/questions/34155418/mongodb-java-driver-mongocore-driver-vs-mongodb-driver-vs-mongodb-async-drive