When inserted object is available for search

I use java driver (sync) and want to be able to search objects by id or field just right after successful insert.
Does MongoDB ensures that after a successful save response, the data will be instantly searchable?

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")
    }
}

This looks like some JavaScript.

If you do not do anything to set some_id in object (or after Document.parse(object)) to someId before the insert, then the server will generate an ObjectId and your find will never succeed because most likely there will never be an object with { some_id : someId }. Unless off course some_id is set to someId outside saveObjectInMongo. But that is error prone as someone might pass a someId that is not some_id. So if some_id is already set to someId outside, you better read it inside saveObjectInMongo and remove the parameter someId.

I am not too sure about the JS driver but you might need async in front of your insertOne call.

Thank you for your answer! This is kotlin and I used java sync driver.
The question was not about id, it was just an example. The main idea was: we insert object and then search it by some fiield like collection.find(eq("field", value)).
The problem is, that I am not sure the object will be searchable immediately after successful insert.

I know the question was not about id. But if I answered yes it is and then you try your sample code, it will most likely failed. Two concepts are fundamental to have a precise answer.

and

So the answer is not simple. But in most cases it will be found specially if in the same process. To be able to give a definitive answer a specific scenario must be presented.

@steevej Thank you. Am I right, that if we use write and read concerns as “majority” the data will be instantly searchable from another thread after write ack? We use only one mongod instance.

Quote from write-concern majority

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.

Yes this is correct.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.