MongoDB cursor detail and instance code
- 2020-06-15 10:25:52
- OfStack
MongoDB cursor detail
Cursors in MongoDB are functionally much the same as cursors in relational databases. A cursor is a pointer to the C language and can be positioned to a record or, in MongoDB, a document. So in mongoDB cursors are defined, declared, opened, read, and closed. With cursors, the client can control the final results effectively, such as limiting the number of results, skipping partial results, or sorting the results by arbitrary combinations of keys in any order. The following is a detailed introduction to the MongoDB cursor.
1. Introduction to mongoDB cursors
db.collection.find() Method returns 1 For access to the document, we need to iterate over the cursor
mongoDB Cursors and relational databases SQL The cursor is similar and can be done by means of a cursor ( Limit the number of query results, skip the number of results, etc ) Settings to control query results
Cursors consume memory and associated system resources, which should be released as soon as possible after cursors are used up
in mongo shell If the returned cursor result set is not specified to a var The cursor iterates automatically 20 Second, before the output 20 A file, beyond 20 In the case of theta, input is required it To turn pages
This article describes how to manually iterate through a document by cursor or by index
Declare cursor
var cursor = db.collectioName.find(query,projection);
Open the cursor
Cursor.hasNext() Determines whether the cursor is terminated
Read the data
Cursor.Next() Take out the bottom of the cursor 1 A document
Close the cursor
cursor.close() This step can be omitted, usually automatically closed, or displayed closed
with while Loop through the cursor example
var mycursor = db.bar.find({_id:{$lte:5}})
while(mycursor.hasNext()) {
printjson(mycursor.next());
}
Cursor life cycle
a After the cursor completes the iteration of matching result, it will clear itself;
b The cursor of the client is no longer in scope, and the driver sends back to the server 1 A special message to be destroyed;
c , the cursor is in by default 10 If it is not used within minutes, the cursor is closed automatically or the client has iterated over the entire cursor;
d , can be passed cursor.noCursorTimeout() To define the cursor timeout
Such as: var myCursor = db.users.find().noCursorTimeout()
e , can be used for custom timeout length cursors cursor.close() To close the cursor
Such as: db.collection.find(<query>).close()
2. Current environment and data preparation
repSetTest:PRIMARY> db.version()
3.0.12
// Create contains 29 A collection of documents user
repSetTest:PRIMARY> for (var i=1;i<30;i++){
... db.user.insert({"id":i,"ename":"usr"+i});
... }
WriteResult({ "nInserted" : 1 })
repSetTest:PRIMARY> db.user.count()
29
// Query the collection user All documents above
repSetTest:PRIMARY> db.user.find()
{ "_id" : ObjectId("5804d07fd974b32430ea9748"), "id" : 1, "ename" : "usr1" }
{ "_id" : ObjectId("5804d07fd974b32430ea9749"), "id" : 2, "ename" : "usr2" }
.............................
{ "_id" : ObjectId("5804d07fd974b32430ea975b"), "id" : 20, "ename" : "usr20" }
Type "it" for more // The above result is output only 20 Line, this prompt indicates to view more should be entered it
repSetTest:PRIMARY> it
{ "_id" : ObjectId("5804d07fd974b32430ea975c"), "id" : 21, "ename" : "usr21" }
..............
{ "_id" : ObjectId("5804d07fd974b32430ea9764"), "id" : 29, "ename" : "usr29" }
2. Output cursor result set using print
repSetTest:PRIMARY> var myCursor = db.user.find()
while (myCursor.hasNext()) {
print(tojson(myCursor.next()))
}
{ "_id" : ObjectId("5804d07fd974b32430ea9748"), "id" : 1, "ename" : "usr1" }
..........
{
"_id" : ObjectId("5804d07fd974b32430ea9751"),
"id" : 10,
"ename" : "usr10"
}
................
{
"_id" : ObjectId("5804d07fd974b32430ea9764"),
"id" : 29,
"ename" : "usr29"
}
// Passed in the above query var myCursor The definition of a variable is equivalent to SQL In the declare cursor cur_name is select ..
// variable myCursor A definition is just a definition. It does not access the database, but in myCursor.hasNext() Real access to the database
//myCursor.next() It's the output 1 Records, hasNext() When the database is accessed, the results are read locally based on the default cursor Settings
3. Output cursor result set using printjsont
repSetTest:PRIMARY> var myCursor = db.user.find({id:{$gt:20}})
while (myCursor.hasNext()) {
printjson(myCursor.next());}
{
"_id" : ObjectId("5804d07fd974b32430ea975c"),
"id" : 21,
"ename" : "usr21"
}
.......
{
"_id" : ObjectId("5804d07fd974b32430ea9764"),
"id" : 29,
"ename" : "usr29"
}
4. Iterate with forEach()
repSetTest:PRIMARY> var myCursor = db.user.find({id:{$gt:20}})
repSetTest:PRIMARY> myCursor.forEach(printjson);
{
"_id" : ObjectId("5804d07fd974b32430ea975c"),
"id" : 21,
"ename" : "usr21"
}
................
{
"_id" : ObjectId("5804d07fd974b32430ea9764"),
"id" : 29,
"ename" : "usr29"
}
5. Iterate based on array index
You can use toArray() to return a cursor iterating document to an array and then access it via array subscripts.
This method loads all documents returned by the cursor into memory.
// In the following example, the contents returned by the cursor are passed into an array and then used printjson (documentArray[3]) Output the elements
repSetTest:PRIMARY> var myCursor = db.user.find({id:{$gt:20}})
repSetTest:PRIMARY> var documentArray = myCursor.toArray();
repSetTest:PRIMARY> printjson (documentArray[3])
{
"_id" : ObjectId("580d775edeb57e4d05eec0f2"),
"id" : 24, //Author : Leshami
"ename" : "usr24" //Blog : http://blog.csdn.net/leshami
}
// You can also output an array element to a variable and use it again printjson(myDocument) Output this variable as follows
repSetTest:PRIMARY> var myDocument = documentArray[3];
repSetTest:PRIMARY> printjson(myDocument)
{
"_id" : ObjectId("580d775edeb57e4d05eec0f2"),
"id" : 24,
"ename" : "usr24"
}
6. Adjust cursor iteration times
// Set the number of iterations displayed as follows 5
repSetTest:PRIMARY> DBQuery.shellBatchSize = 5
5
repSetTest:PRIMARY> db.user.find()
{ "_id" : ObjectId("5804d07fd974b32430ea9748"), "id" : 1, "ename" : "usr1" }
{ "_id" : ObjectId("5804d07fd974b32430ea9749"), "id" : 2, "ename" : "usr2" }
{ "_id" : ObjectId("5804d07fd974b32430ea974a"), "id" : 3, "ename" : "usr3" }
{ "_id" : ObjectId("5804d07fd974b32430ea974b"), "id" : 4, "ename" : "usr4" }
{ "_id" : ObjectId("5804d07fd974b32430ea974c"), "id" : 5, "ename" : "usr5" }
Type "it" for more // As can be seen from the above query results, when output 5 A document is prompted for input it To see more
repSetTest:PRIMARY> it
{ "_id" : ObjectId("5804d07fd974b32430ea974d"), "id" : 6, "ename" : "usr6" }
{ "_id" : ObjectId("5804d07fd974b32430ea974e"), "id" : 7, "ename" : "usr7" }
{ "_id" : ObjectId("5804d07fd974b32430ea974f"), "id" : 8, "ename" : "usr8" }
{ "_id" : ObjectId("5804d07fd974b32430ea9750"), "id" : 9, "ename" : "usr9" }
{ "_id" : ObjectId("5804d07fd974b32430ea9751"), "id" : 10, "ename" : "usr10" }
Type "it" for more
7. View cursor measurements
Can be achieved by db.serverStatus() View information about the cursor state, which typically includes
The number of cursor timeouts since the server was last started
Customize the number of cursor timeouts
The cursor has been opened pinned The number of
Total number of open cursors
// The following queries the information for the native cursor
repSetTest:PRIMARY> db.serverStatus().metrics.cursor
{
"timedOut" : NumberLong(2),
"open" : {
"noTimeout" : NumberLong(0),
"pinned" : NumberLong(0),
"total" : NumberLong(2)
}
}
Thank you for reading, I hope to help you, thank you for your support to this site!