Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoCollection.find() does search twice?

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

like image 917
Chirag Mehta Avatar asked May 06 '26 07:05

Chirag Mehta


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.

like image 167
Pranav Nachnekar Avatar answered May 09 '26 14:05

Pranav Nachnekar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!