4

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

2
  • Where is your query being run? Is it on the server side? Or is it being run on the client end? Commented Dec 2, 2012 at 19:13
  • @Ivan, the query is direct on the mongo console. (with the command "mongo"). The DB is locally installed on my machine. I already figured out how to make it. thanks. Commented Dec 3, 2012 at 8:18

2 Answers 2

14

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.

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

4 Comments

I am unsure if sort() works on findOne since it does not return a cursor as such the chain will have no function of sort()
Hi, thanks for your answer. I keep getting this error: "Sun Dec 2 21:58:13 TypeError: db.drives.findOne({}, {_id:0, driveDate:1}).sort is not a function (shell):1"... somehow findOne can't work with sort
@otmezger Sorry about that, Sam's right, there doesn't seem to be a way to sort with findOne in the shell. See updated answer.
I'd like to share my wtf experience. I was doing let tmp = db.collection.aggregate(...).map(doc => doc._id) in IntelliJ IDEA DataGrip to later use the variable in another query $match: { "foo": { $in: tmp } }. But I faced WriteAbortedException; NotSerializableException: TruffleStackTraceElement error. The solution was to append .toArray() as in your example. Thank you!
5

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

Comments

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.