[Mr. Zhao Qiang] using cursors in mongodb


[Mr. Zhao Qiang] using cursors in mongodb

1、 What is a cursor?

Cursor is a method of processing data. In order to view or process data in result set, cursor provides the ability to browse data forward or backward one or more rows at a time in result set.

A cursor is actually a mechanism that can extract one record at a time from a result set that contains multiple data records. The cursor can be regarded as a temporary file composed of a query result set (which can be zero, one or multiple records retrieved by related selection statements) and a cursor position pointing to a specific record in the result set. It provides the ability to browse data forward or backward in the query result set and process data in the result set. With a cursor, users can access any row of data in the result set. After placing the cursor on a row, they can perform operations on that row or from the row block at that location.

2、 Mongodb’s cursor

In mongodb, use the db.collection.find () method will return a cursor. To access the document, we need to use the iterator of the cursor. However, in the Mongo shell, if no variable is specified for the returned cursor, the cursor will automatically return the first 20 records first. Here are a few specific examples to show how to use cursors.

  • Define cursor
var mycursor = db.emp.find()
  • Using cursors to access documents
var mycursor = db.emp.find()

It can also be like this: mycursor.forEach (printjson)
  • Cursors and arrays
var mycursor =  db.emp.find () define cursor
var myarray  =  mycursor.toArray () convert cursor to array
Var mydocument = myArray [3] accessing documents through array elements
  • Paging queries: skip and limit
5 records per page
var mycursor =  db.emp.find (). Limit (5) page 1
var mycursor =  db.emp.find (). Limit (5). Skip (5) page 2

Close cursor: by default, cursors that are not used within 10 minutes will be automatically closed. You can use. Nocursortimeout() to set the cursor’s close option. You need to close the cursor manually.

var mycursor = db.emp.find().noCursorTimeout()

[Mr. Zhao Qiang] using cursors in mongodb