MongoCollection.find() does search twice?

Viewed 47

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

1 Answers

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.

Related