- [Trainer] Finally let's implement the logic
that will fetch the maximum value
and its state from the database.
For that, I will scroll down to the getMax method.
So how can we get the maximum value?
The most efficient way in MongoDB
is actually by using sorting.
This means I will vary the database,
sort by the value in descending order,
and then get just one element from it
which is then naturally of course, the highest value
and this can achieved but just one line of code.
So I return this.ollection,
and on collection there is this method findOne
which will return exactly one document
and here I would have the queries.
So if I want to find one specific document
I would have the very year,
but in our case we want to query all documents,
but then a second argument I can pass in options
and in our case I will pass in sort
and I want to sort by value
and to make it in descending order,
I add colon minus one.
So this will sort now the results set
by value in descending order.
Now I have to call this again so way down
after the insert operation did run
I will now add console.info("Querying MongoDB")
and I will also start time again,
console.time("MongoDB-find") and in this case,
it's a find operation and then I can already
call my getMax function
and then of course I want to get the return value
because that's our document
so add const.doc equals await this.getMax.
And then I stop the timer
with console.timeEnd("MongoDB"-find).
And now all I have to do is to return the result now
and I have to do this after the disconnect took place too
at the very end from our MAX function, I will now return.
And in our case, I don't want to return the whole object
because that also contains the ID.
I just want to return date and values,
so return an object date: doc.date,
and add a property value: doc.value.
You might have figured that if we run this now again,
we will also insert all the documents again
into the database.
This is of course, something you want to do in real life.
There you will have ways to make sure
that you don't add the same data again and again.
In our case and for demonstration purposes,
I'm even interested in that
because the more documents are in the database,
the longer it might take to fetch data
from it also to insert data from it.
So this gives an interesting metric
for our cost scenario here on how the database behaves.
So let's try this now out.
I will run npm start
and get back the maximum value which was in 2017
and it was roughly over $19,000.
That's plenty.
And how long did this query take?
So this query took us 15 milliseconds.
That's not so much, but the insert operation
was rather expensive with 500 milliseconds.
We can now also get the minimum value obviously.
So if we get to go to getMax
and just change the order into one,
so now I'm sorting in ascending order.
Let's run it again.
We see that in 2015, the lowest value
over the last five years was around $241.
So this concludes our first basic example for using MongoDB.