Query Builder Lecture (Efficiency question)

Hi, prior to taking up this course, I had been returning queried documents in such way,

Document doc = collection.find(query).first()

Is there any performance difference if I were to follow the lecture way of writing,
Document doc = collection.find(query).iterator().tryNext() ?

The differences may be minimum, but I want to know in definite, which is better? Because I am working on a project right now and the entire code uses “.first()”.

Hi @Joseph_41286,

Interesting question! :slight_smile:

When we send a find command to the server, the java driver send within the command with a set of cursor options like limit, sort, batchSize project etc…

  1. When we execute the find().iterator.tryNext() command, we are sending with the default settings:

    • no limit, no skip, no batchSize etc
  2. When we issue the first() command, we actually send the command with:

    • limit 1
    • batchSize 1

So, first() is slightly faster. But the speed/performance will be same if we set all the cursor options with find command like this:



1 Like

Thank you! It is certainly helpful to know that.