Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo db shell variable printing only once

> var x = db.sampleDB.find();
> x

output:

{ "_id" : ObjectId("55d02ed690ddbaafbfe20898"), "name" : "aditya", "city" : "meerut" }

But if I print this variable again, it does not printing anything. and I am not able to print x.name?

using ubuntu 14.04(db version v2.6.10)

like image 422
aditya Avatar asked Aug 16 '15 07:08

aditya


1 Answers

The result returned from .find() is a "cursor" and not a value. So when you do something like:

> var x  = db.sampleDB.find();
> x

Then all you are doing is iterating the cursor just as if you did:

> db.sampleDB.find();

If you wanted to "keep" the content, then call .toArray()

> var x  = db.sampleDB.find().toArray();
> x

Or if the result is singular, then just call .findOne()

> var x  = db.sampleDB.findOne();
> x

These have now all been "converted" from a cursor, which only retrieves results once, in to variable that already has the fetched results.

like image 113
Blakes Seven Avatar answered Oct 20 '22 09:10

Blakes Seven