2

I am using the code snupped as below :

if (collection.find(toFind) != null) {
            dataFound = collection.find(toFind).first();
        } else {
            System.err.println("NULL");
        }

As collection.find() is being called twice here, will that be performing 2 searches on database or becasue it returns a FindIterable, its just a cusror???

We are restricted to limit the database operations and avoid as much necessary, as we are paying it per request unit

Chirag Mehta
  • 25
  • 1
  • 6
  • 2
    Why do you need that null check in the first place? Wouldn't find always return a result, even if it is empty? – Thilo Jul 01 '19 at 13:30
  • YES - FindIterableImpl will return a result..even if its empty. I can modify my check like - `if (collection.find(toFind).count() > 0) { dataFound = collection.find(toFind).first(); } else { System.err.println("EMPTY"); }` but still the question remain, whether the .find() will be called twice ?? i would expect it would return a cursor and the cursor will not close until a further operation like first(), sort(), filter(), etc are called Does that clarify my original question? Any documentation around that – Chirag Mehta Jul 03 '19 at 11:37

1 Answers1

2

Why not store the find result and then use the store variable

var queryResult = collection.find(toFind)
if(queryResult != null){
 dataFound = queryResult.first()
} else { // Handle error here}

Or better yet just use the findOne method to get the first result

var queryResult = collection.findOne(toFind)
if(!queryResult){
  //Handle result here
}

And to answer the question, yes it will perform the query twice.

Pranav Nachnekar
  • 115
  • 1
  • 10