Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between find and findOne

Tags:

mongodb

when a variable say testVar is assigned with result of findOne, its availability is endless. But a variable assigned with result of find() availability is only once. Below is the command prompt dump

> var testVar = db.basic.findOne()
> testVar
{ "_id" : ObjectId("52abd2737164a542e93f1ebe"), "name" : "MongoDB" }
> testVar
{ "_id" : ObjectId("52abd2737164a542e93f1ebe"), "name" : "MongoDB" }
> testVar
{ "_id" : ObjectId("52abd2737164a542e93f1ebe"), "name" : "MongoDB" }


> var testVar = db.basic.find({"name":"MongoDB"})
> testVar
{ "_id" : ObjectId("52abd2737164a542e93f1ebe"), "name" : "MongoDB" }
> testVar
> testVar
>
like image 206
auhuman Avatar asked May 11 '26 03:05

auhuman


1 Answers

findOne returns a single document, where find returns a cursor. Once you go through the cursor of find, you are at the end, and there are no more documents.

like image 182
Jeff Storey Avatar answered May 13 '26 01:05

Jeff Storey



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!