7
> 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)

styvane
  • 59,869
  • 19
  • 150
  • 156
aditya
  • 149
  • 1
  • 3
  • 15

1 Answers1

11

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.

Blakes Seven
  • 49,422
  • 14
  • 129
  • 135
  • This article shows some more options for working with cursors in the shell: https://docs.mongodb.org/manual/tutorial/iterate-a-cursor/ – Steve Tarver Oct 25 '15 at 04:17