MongoDB find vs findOne

No Comments

I got hit by this newbie bug. The exercise entails getting a specific record from the database, storing it in a variable, updating it a few times and saving it in the database after each update. Sounds simple, until I am perplexed that I cannot view the variable more than once. The second invocation is just showing or returning an empty string.


> var myobject = db.products.find({_id : ObjectId("507d95d5719dbef170f15c00")})
> myobject
{ "_id" : ObjectId("507d95d5719dbef170f15c00"), "name" : "Phone Service Family Plan", "type" : "service", "monthly_price" : 90, "limits" : { "voice" : { "units" : "minutes", "n" : 1200, "over_rate" : 0.05 }, "data" : { "n" : "unlimited", "over_rate" : 0 }, "sms" : { "n" : "unlimited", "over_rate" : 0 } }, "sales_tax" : true, "term_years" : 2 }
> myobject
>
> //why cant i display the object contents again?
>

It turned out that I should have used db.products.findOne instead. The findOne function returns an actual document record while the find function returns a cursor. Yes, the cursor moved the pointer on the next record after each read request which means that subsequent read calls to it are getting nothing since the cursor was already pointing to the “end of cursor” location after the first read, if I correlate that correctly with how cursors in relational databases work.

Great to know. I want my 15 minutes back. 🙂

ciao!