udexter
udexter

Reputation: 2347

MongoCollection findOne vs find

I would like to know if there is some improvement on MongoCollection::findOne or if is just an "alias" or "shorcut" to MongoCollection::find with a limit of 1, for example.

Thank you

Upvotes: 0

Views: 2902

Answers (6)

Gates VP
Gates VP

Reputation: 45287

findOne() is an alias of find() with a limit(-1)

You can see this in the source code here. It does the equivalent to

find(...).limit(-1).getNext().

The -1 is actually relevant. Here's a snippet from the wire protocol docs:

If the number is negative, then the database will return that number and close the cursor.

If you go to the shell and type > db.collection.findOne (no parens), you can see that the function is also just a helper in the shell.

So, "yes findOne() is just a helper".

Upvotes: 5

Lycha
Lycha

Reputation: 10177

mongodb.org has an performance test report where they compared findOne and find. Based on the results it would seem that findOne is 35-45% faster.

Few data points from the report:

  • find_one (small, no index): 989 Ops/s
  • find (small, no index): 554 Ops/s

Upvotes: 1

aziz punjani
aziz punjani

Reputation: 25776

It depends on your search query. E.g if you search by ID, since ID is unique it would not need to limit the results because only one result would be found. If more than one record is found then it would limit the results by 1. Another difference is that findOne returns an array, while find returns a mongoCursor.

Upvotes: 0

Herzult
Herzult

Reputation: 3419

The MongoCollection::findOne method will directly return the result array and the MongoCollection::find one will return a MongoCursor instance even if it is a single valued result.

Upvotes: 1

jpredham
jpredham

Reputation: 2199

From the mongo tutorials...

To show that the document we inserted in the previous step is there, we can do a simple findOne() operation to get the first document in the collection. This method returns a single document (rather than the DBCursor that the find() operation returns), and it's useful for things where there only is one document, or you are only interested in the first. You don't have to deal with the cursor.

Upvotes: 2

Martin Samson
Martin Samson

Reputation: 4090

It is almost like an alias but instead of return you a list, it returns you an object.

Upvotes: 0

Related Questions