Now this is actually it for the query selectors and operators.
Let's now briefly come back to that cursor thing which I already touched on earlier in this course, the
find method unlike the findOne method, yields us a cursor
if you remember.
Now why is that important and why does it do that? Well if we have our client communicate with the mongodb
server,
we potentially get back thousands or even millions of documents with find, especially if we have no
condition in there
but even with a condition, you easily have a condition that still meets like 1000 documents or more
depending on the scale of your app.
So you get back all these results and that is very inefficient because all these results have to be
fetched from the database,
they have to be sent over the wire and then they have to be loaded into memory in your client application.
So these are three things that are not optimal because chances are you will not need all thouand documents
at the same time and therefore, find gives you a cursor. A cursor is basically a pointer which has the
query you wrote stored and which can therefore quickly go to the database and say hey, give me the next
batch,
give me the next batch
and indeed you work with batches of data then. You fetch the data one by one, so one document by a time
and it really is only transferred over the wire when you request the next one.
Now in the shell, we get 20 by default because the shell automatically basically takes the cursor and gets
us the first 20 documents before we can get more.
If you write an application with a mongodb driver and we'll see that in the from driver to
shell module
at the end of the course, then you have to control that cursor manually and make sure you get back your
results. And that cursor approach is
great because it saves resources.
If you have a query that meets 1000 documents, but let's say you have a website where you only display
10 items, let's say 10 products you fetched at a time anyways, then there is no need to load all thousand
results that matched your query right at the start.
Instead you would only fetch the first 10,
display them on the screen and then go ahead and fetch the next 10
when the user navigated to the next page or anything like that. This is the idea behind a cursor,
now we'll find out how to work with a cursor
later as I mentioned when I talk about how you use the mongodb driver in a real application
but I can already show you some things in this module.
So in the next lectures, we'll play around with the cursor a bit.