Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to save a result from a mongodb query into a javascript variable?

there are some questions here regarding how to save a result from a query into a javascript varialbe, but I'm just not able to implement them. The point is that I have a much difficult query, so this question is, in my opinion, unique.

Here is the problem. I have a collection namend "drives" and a key named "driveDate". I need to save 1 variable with the smallest date, and other with the biggest date.

The query for the smallest date is:

> db.drives.find({},{"_id":0,"driveDate":1}).sort({"driveDate":1}).limit(1)

The result is:

{ "driveDate" : ISODate("2012-01-11T17:24:12.676Z") }

how dan I save this to a variable, can I do something like:

tmp = db.drives.find({},{"_id":0,"driveDate":1}).sort({"driveDate":1}).limit(1)

Thanks!!!

like image 532
otmezger Avatar asked Dec 05 '22 13:12

otmezger


2 Answers

Assuming you're trying to do this in the shell:

 tmp = db.drives.find({}, {_id:0, driveDate:1}).sort({driveDate:1}).limit(1).toArray()[0]

find returns a cursor that you need to iterate over to retrieve the actual documents. Calling toArray on the cursor converts it to an array of docs.

like image 93
JohnnyHK Avatar answered Dec 28 '22 10:12

JohnnyHK


After some time figuring out, I got the solution. here it is, for future reference:

var cursor = db.drives.find({},{"_id":1}).sort({"driveDate":1}).limit(1)

Then I can get the document from the cursor like this

var myDate = cursor.next()

That's it. Thanks for your help

like image 40
otmezger Avatar answered Dec 28 '22 09:12

otmezger