Search code examples
javamongodbsynchronous

Does MongoDB ensures that after a successful save response, the data will be instantly searchable


I am working on a java/kotlin project where the just saved object should be immediately searchable. Just like synchronous saving in sql databases (PostgreSQL). I read that MongoDB Java Drivers provides both synchronous and asynchronous interaction with MongoDB.

But does MongoDB ensures that after a successful save response, the data will be instantly searchable? Maybe it has an inner queue for not yet realy saved data like in Elasticsearch and Couchbase?

In other words will an exception ever be thrown? For example under heavy load. We assume that someId = object.some_id.

fun saveObjectInMongo(collection: MongoCollection<Document>, someId: String, object: String) {
    collection.insertOne(Document.parse(object))
    if (collection.find(eq("some_id", someId)).first().isNullOrEmpty()) {
        throw RuntimeException("Can't get just saved object")
    }
}

Solution

  • The main concept is a correct usage of write/read concerns. For this case majority concern is needed.

    "After the write operation returns with a w: "majority" acknowledgment to the client, the client can read the result of that write with a "majority" readConcern."

    https://docs.mongodb.com/manual/reference/write-concern/ https://docs.mongodb.com/manual/reference/read-concern/