gotchaMajor
Difference between MongoDB's find and findone calls
Viewed 0 times
callsmongodbdifferencefindonebetweenfindand
Problem
I am working on a project and I am unsure if there is a difference between the way the
find cursor works and the way the findOne cursor works. Is findOne just a wrapper for find().limit(1)? I was looking around for it and maybe someone knows if mongodb has a special method for it or not. I am working with the PHP API for mongodb if that makes a difference.Solution
Based on my own benchmarks,
There is either an error in the MongoDB documentation or a bug in
update: response from a 10gen (MongoDB) engineer:
The two queries you are executing are very different. A find query
returns a cursor, this is essentially a no-operation scenario, as no
actual data is returned (only the cursor information). If you call
findOne, then you are actually returning the data and closing the
cursor. The docs should definitely be clearer :-)
Update: Indeed, if the
find().limit(1) is orders of magnitude faster than findOne().There is either an error in the MongoDB documentation or a bug in
findOne(). findOne() performs more like find().limit(N) where N is the number of documents the query would return. I figured this out while trying to figure out why my simple queries were so slow!update: response from a 10gen (MongoDB) engineer:
The two queries you are executing are very different. A find query
returns a cursor, this is essentially a no-operation scenario, as no
actual data is returned (only the cursor information). If you call
findOne, then you are actually returning the data and closing the
cursor. The docs should definitely be clearer :-)
Update: Indeed, if the
find().limit(1) document is retrieved, the orders of magnitude speed difference seems to disappear. Also, I could not reproduce the major speed difference with the MongoDB JavaScript driver. I originally benchmarked using the MongoDB Java driver.Context
StackExchange Database Administrators Q#7573, answer score: 37
Revisions (0)
No revisions yet.