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 ?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With