MongoDB Panache return void for write operations

Viewed 643

In 'plain vanilla' MongoDB, methods that do a write operation into the DB, such as .insertOne() or .deleteOne(), will return an InsertOneResult or DeleteResult respectively. These objects will return a boolean value for acknowledged and an id where applicable. This allows us to ensure that the write operation was successful.

However, in Panache, the MongoOperations.class is returning void:

MongoOperations.class

private static void persist(MongoCollection collection, Object entity) {
    collection.insertOne(entity);
}

The question then is, how can we retrieve the resulting InsertResult and DeleteObject object?

pom dependency being used

<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-mongodb-panache</artifactId>
    <version>1.5.0.Final</version>
1 Answers

This is a design choice.

We choose to make MongoDB with Panache as close as possible to Hibernate with Panache so persist() and delete() returns void.

We didn't want to expose MongoDB related API (so not returing InsertOneResult or DeleteResult) neither.

So, your question is about accessing the acknowledged boolean to be sure that the operation has been acknowledged on MongoDB side, and the id in case you create new documents and let MongoDB manage the identifier for you.

Here are some answers:

  • The id is computed before insertion to the database, you can retrieve it from the entity after having call the persist() operation, it would have been populated by the MongoDB driver.
  • The default write concern for MongoDB is w:1 meaning that the operation will succeed if the master (or the standalone) node has acknowledged the operation. This means that by default, if the call to persist() didn't throw an exception the operation has been acknowledged. Unless you configure MongoDB with a write concern of w:0, as soon as the persist() operation succeed this means the document has been inserted to the database.
  • For the delete() operation, the same write concern rules applies. But we didn't check that the document has been deleted (we didn't check deletedCount to be 1), maybe it's an oversigth, and we may have done it. If you think we should, you can open an issue in Quarkus Github repository (this may break backward compatibility so we will need to be careful about this).
Related