Introduction to MongoDB cursor operations

Rama Sagar
Posted by in NoSql category on for Beginner level | Points: 250 | Views : 6621 red flag

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.
Recommendation
Read Introduction to MongoDB finding Documents Part 2 before this article.

Introduction

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:

·         Introduction to Mongo Database

·         Introduction to Mongo DB setting up the server

·         Introduction to Mongo DB Command Line options

·         Introduction to Mongo DB install as a service

·         Introduction to Mongo DB Mongo Shell

·         Introduction to Mongo DB Replica set

·         Introduction to Mongo DB Storing Data 

·         Introduction to Mongo DB Storing Data Part 2

·         Introduction to Mongo DB Updating document

  


Objective

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.


Sorting 

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




Conclusion

In this article we have seen the different ways of performing cursor operations in mongodb

Reference

http://www.mongodb.org/ 

Page copy protected against web site content infringement by Copyscape

About the Author

Rama Sagar
Full Name: RamaSagar Pulidindi
Member Level: Silver
Member Status: Member,MVP
Member Since: 12/30/2012 1:51:40 AM
Country: India
ramasagar
http://www.ramasagar.com
A Software Profesional working in Microsoft .NET technologies since year 2008, and I work for Dake ACE. I am passionate about .NET technology and love to contribute to the .NET community at Dot Net Funda

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)