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)

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This article shows some more options for working with cursors in the shell: docs.mongodb.org/manual/tutorial/iterate-a-cursor

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.