Get the App
SLTechnology News&Howtos  ›  Database  › 

Vernier

Shulou Source: shulou.com Published: 2022-06-01 21:55:31 10月03日 Update

Cursor operation cursor

What is the cursor?

Popularly speaking, cursors are not query results, but query return resources, or interfaces.

Through this interface, you can read it one by one.

Just like fopen in php opens a file and gets a resource, you can read the file line by line through the resource.

Declare cursors:

Var cursor = db.collectioName.find (query,projection)

Cursor.hasNext () to determine whether the cursor has been fetched to the end

Cursor. Next (), which fetches the next unit of the cursor

Use while to loop cursors

Var mycursor = db.bar.find ({_ id: {$lte:5}})

While (mycursor.hasNext ()) {

... Printjson (mycursor.next ())

...}

(note: when you call next (), the cursor has reached the second one, so a _ id of 1 will not output. If there is no next one, there will be an error.)

Example:

/ / declare cursors

Var cursor = db.goods.find ()

/ / Loop cursor

For (var doc=true;cursor.hasNext ();) {printjson (cursor.next ());}

It can also be abbreviated:

For (var cursor=db.goods.find (), doc=true;cursor.hasNext ();) {printjson (cursor.next ());}

The cursor also has an iterative function that allows us to customize the callback function to process each unit one by one.

Cursor.forEach (callback function)

Example:

Var gettitle = function (obj) {print (obj.goods_name)}

Var cursor = db.goods.find ()

Cursor.forEach (gettitle)

Application of Vernier in pagination

For example, look up to 10000 lines, skip 100 pages and take 10 lines.

In general, we assume that there are N lines per page, which is currently a page page

You need to skip the previous (page-1) * N line, and then take the N line. In mysql, limit offset,N implements it.

In mongo, it is realized by skip () and limit () functions.

For example, var mycursor = db.bar.find () .skip (9995)

In the query result, skip the first 9995 rows

Query page 901, 10 articles per page

Is var mytcursor = db.bar.find () .skip (9000) .limit (10)

Get all the data at once through cursor and return the array.

Example:

Var cursor = db.goods.find ()

Printjson (cursor.toArray ()); / / see all lines

Printjson (cursor.toArray () [2]); / / see line 2

Note: do not use toArray () casually

Reason: all rows are immediately organized in memory in the form of objects.

You can use this feature when fetching a few lines.

Tags: Cursors functions queries resources lines units interfaces files results loops popular one-time memory functions reasons objects forms data arrays abbreviations Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Shulou Tech Info OPPO Reno Microsoft macOS