[Mr. Zhao Qiang] use cursor in mongodb

Time:2021-9-23

1、 What is a cursor?

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

Cursors are actually a mechanism that can extract one record at a time from a result set that includes 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 relevant selection statements) and the cursor position pointing to specific records in the result set, which 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 the row or the row block from that position.

2、 Mongodb cursor

In mongodb, using the DB. Collection. Find () method will return a cursor. If we want 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. Let’s illustrate how to use cursors through several specific examples.

  • Define cursor
var mycursor = db.emp.find()

 

  • Accessing documents using cursors
var mycursor = db.emp.find()
while(mycursor.hasNext()){
    printjson(mycursor.next())
}

It can also be like this: myCursor. For each (printjson)

 

  • Cursors and arrays
Var myCursor = dB. EMP. Find() defines the cursor
Var myArray = myCursor. Toarray() turns cursors into arrays
Var mydocument = myArray [3] accessing documents through array elements

 

  • Paging query: 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 closed automatically. You can use. Nocursortimeout() to set the cursor closing option. In this case, you need to close the cursor manually.

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

 

Recommended Today

A detailed explanation of the differences between Perl and strawberry Perl and ActivePerl

Perl is the abbreviation of practical extraction and report language “practical report extraction language”. Application of activestateperl and strawberry PERL on Windows platformcompiler。 Perl   The relationship between the latter two is that C language and Linux system have their own GCC. The biggest difference between activestate Perl and strawberry Perl is that strawberry Perl […]