Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variables not set in mongo shell

I am trying to work with mongo shell and I am having challenges in storing the value inside of mongo shell

when I find a user in the document users, i store it in the variable doc

> var doc = db.users.find({"username":"anil"});

When I type doc in the mongo shell i see the json object

> doc
{ "_id" : ObjectId("57325aaa48d9231b11e5cb81"), "username" : "anil", "email" : "[email protected]" }

However when I type doc again, i dont see anything. its gone.. what am I doing wrong here ?

> doc
>

It might be something simple but I am not getting it. Can someone point out what I am doing wrong ?

like image 933
user641887 Avatar asked May 11 '16 20:05

user641887


2 Answers

This because find returns a cursor and you can only consume all the value once. Here because you filter your document based on _id value, in the return cursor you only have one document which is consumed the first time you time. If you need to iterate your result many times, you will need to return an array that contains all the documents from the cursor using toArray, but in your case what you need is findOne

like image 87
styvane Avatar answered Oct 17 '22 01:10

styvane


when you open a mongo shell it tries to find a mongod server and connects to test by default. when you assign some variable in mongo shell to some document in mongod, it actually fetches the document from the database, to get the same result again you need to connect to the database again (means you need to type var doc = db.users.find({"username":"anil"}); again). Unlike the scenario where you define var doc = 4 in shell and typing doc will return 4 every time.

If you want to stop transmission at the beginning and do some processing then you need to add null after it like

var doc = db.users.find({"username":"anil"});null; // do your work on doc

an ex.

enter image description here

like image 29
amitava Avatar answered Oct 16 '22 23:10

amitava