In the mongo shell, the primary method for the read operation is the db.collection.find() method. This method queries a collection and returns a cursor to the returning documents.
In this article we will learn how to do cursor operations in MongoDB with a practical example
Previous articles have provided an introduction to MongoDB and the set up and installation, and few command line options.You can get them from the following:
The objective of the article is to learn how to perform cursor operations Mongo database.
Lets look at the cursor operations available in the shell
For example if we issue the query as shown
The shell has enumerated all other documents matching the criteria.
Now lets capture this cursor into a variable and we can look at the cursor size as shown
To support iterating to the cursor we can query the cursor whether it had items we can see that it had items as shown.
if we want to iterate to the cursor in mongo db we have the foreach method as shown below
so we iterated through the whole cursor and for each one we executed a function.
The more obvious and popular cursor option is sorting
Now lets find some animals in our animals database and retrieve there names and sort them by the name
The sort direction positive is Ascending and negative is descending
ConclusionIn this article we have seen the different ways of performing cursor operations in mongodb