LECTURE - How Cursor works in find()
A free video tutorial from Bogdan Stashchuk
Software Engineer, CCIE #22608, MBA, PhD - stashchuk.com
4.7 instructor rating • 15 courses • 179,179 students
Learn more from the full courseComplete MongoDB Administration Guide
10:15:02 of on-demand video • Updated February 2021
- Deeply understand how MongoDB works - cursor, batch size, iterator
- Launch production database on the Atlas MongoDB - managed cloud-based MongoDB database
- Install and configure production MongoDB on the dedicated or virtual private server
- Understand and use different MongoDB BSON types - ObjectId, ISODate, NumberInt etc.
- Learn how to use MongoDB Shell, Robo 3T (Robomongo), MongoDB Compass for database management
- Perform different kinds of update operations using operators $set, $rename, $addToSet, $push, $inc etc
- Use different kinds of queries and query operators like $in, $eq, $regex, $elemMatch etc.
- Easily combine different aggregation stages like $match, $group, $unwind
- Understand purpose of the indexes and create indexes
- Use backup and restore tools - mongoexport, mongoimport, mongodump and mongorestore
English Let's discuss implementation of the cursor technique in MongoDB. Cursor is used in MongoDB for documents retrieval from MongoDB server. Let's look at the diagram. On the left side there is MongoDB client that needs to retrieve some documents and MongoDB server on the right side that has these documents in its database. In the first step MongoDB client performs "find" operation or invokes Find method maybe with some arguments. MongoDB server receives this request. And suppose that 11 documents match this find query. You may thought before that all those documents will be immediately sent to the client. But it's not the case. MongoDB server returns just cursor to the client. No documents at this moment. When a client receives this cursor it can start requesting documents from the server. Let's suppose that client will make its first request, it is called "Batch request". Why "Batch"? Because client can request set of documents in one shift. Not just one document. But for example 3 like in this example. And server sends 3 documents back to the client. Then MongoDB client may issue next Batch request for the next 3 documents. And server will send those 3 documents back to the client. And so on. This process may go on until there are documents in the cursor. When cursor is exhausted, it means that there are no documents left, and process finishes. In this example 11 documents match "find()" request and batch size is just 3 documents. Of course you can request documents from the server one by one. But it's not efficient. That's why batch size is used and usually it's 20, 50 or 100 documents depending on your needs. In the next section we will look at this in action and practice in MongoDB Shell. See you.