I did this course early last year, and I too had some questions like that then. I will try to answer some of your questions now.
The result set is the actual documents returned by the query; but is on the database server. In the client program, the
mongo shell, you get a cursor (which points or refers or gives access to the result set). You can think the cursor is like an API or a program to work with the result set.
The cursor has many methods which can be run. Some methods affect the result set and some provide the status or info about the result set.
The cursor also maintains some information about the result set. Some information can change as you use the result set data by applying cursor methods.
Cursor has many methods: See Cursor Methods.
You apply these methods and use the returned information or data to suit your application, i.e., what you want to do with the query data in the shell.
Working on the result set using the cursor and its methods:
We will discuss some methods here.
count() returns the count of the number of documents in the result set initially. It is always constant at any point. This is information.
As you read documents from the result set (using cursor’s methods), the result set gets exhausted. Once exhausted you cannot read any more.
hasNext() tells if there are any documents available to be read. Returns a boolean
next() returns a document if available (you first check with
hasNext, and then do a
If you do a
hasNext will return
next will throw an error.
itcount() returns the count of remaining documents (as a number) in the result set and exhausts it (similar to the
sort() sorts the documents in the result set.When you fetch the documents using
toArray, you get the documents in sorted order.
limit() is used to get the maximum number of documents the cursor can return to you.
test collection has 60 documents.
var cur = db.test.find().limit(25) creates a result set from which you can get maximum 25 documents only.
cur.count() will show 60, which is the actual count of documents by the query; this is information.
next() will return a document.
itcount() will return 24 (and exhausts the cursor).
itcount() again returns 0.
Those are some basic features of cursor and result set. There are many cursor methods, and you can try and see how they work and get a better understanding.
P.S.: Also see: Iterate a Cursor in the