Learning MongoDB 6: MongoDB query (cursor operation, cursor information) (3), mongodb cursor

Source: Internet
Author: User
Tags findone mongodb query mongodb server mongo shell

Learning MongoDB 6: MongoDB query (cursor operation, cursor information) (3), mongodb cursor
I. Introduction

Db. collection. find () can be used to query based on conditions and specify fields returned using the projection operator to omit this parameter to return all fields in the matching document. The cursor of the matching document is returned. You can modify the query restrictions, jumps, and sorting order functions at will.

 

Ii. db. collection. findOne ()

Db. collection. findOne () returns documents that meet the specified query conditions. If multiple documents meet the query requirements, this method returns the first document, which returns the order of files on the disk in the natural order. In the overwrite set, the natural order is the same as the insertion order.

Syntax:

   db.collection.findOne(query, projection)


Parameters

Type

Description

Query

Document

Optional. Use the query operator to specify the query conditions.

Projection

Document

Specifies that the field returned by the projection operator is omitted. This parameter returns all fields in the matching document.

 

Projection Syntax:

 

 { field1: <boolean>, field2: <boolean> ... }


Note:

1 Or true indicates the returned Field

0 or false indicates that this field is not returned.


Insert data first

>db. orders.insert([{        "onumber" : "001",         "date" : "2015-07-02",         "cname" : "zcy1",         "items" :[ {        "ino" : "001",                  "quantity" :2,                   "price" : 4.0         },{                 "ino" : "002",                  "quantity" : 4,                   "price" : 6.0           }         ]},{        "onumber" : "002",         "date" : "2015-07-02",         "cname" : "zcy2",         "items" :[ {                  "ino" : "001",                  "quantity" :2,                   "price" : 4.0                 },{                  "ino" : "002",                  "quantity" :6,                   "price" : 6.0                  }               ]}])

Multiple records are returned when we use db. orders. find () to query.

   >db.orders.find({"date":"2015-07-02"})

 

When db. orders. findOne () is executed, only the first record is returned.

 

Example:

<span style="font-size:18px;">  >db.orders.findOne({"date":"2015-07-02"})</span>

 

Ii. cursor Traversal

Db. collection. find () can be used to query based on conditions and specify fields returned using the projection operator to omit this parameter to return all fields in the matching document. The cursor of the matching document is returned. You can modify the query restrictions, jumps, and sorting order functions at will.

1. We first fill in 10000 documents in the collection using a javascript script, and then execute db. collection. find () to execute the query document.

> for(var i=0;i<10000;i++){...db.items.insert({"ino":i,"quantity":i});... }WriteResult({ "nInserted" : 1 })> db.items.find(){ "_id" :ObjectId("55a66f3c7db4e9f2ef681076"), "ino" : 0,"quantity" : 0 }{ "_id" :ObjectId("55a66f3c7db4e9f2ef681077"), "ino" : 1,"quantity" : 1 }{ "_id" :ObjectId("55a66f3c7db4e9f2ef681078"), "ino" : 2,"quantity" : 2 }{ "_id" :ObjectId("55a66f3c7db4e9f2ef681079"), "ino" : 3,"quantity" : 3 }{ "_id" : ObjectId("55a66f3c7db4e9f2ef68107a"),"ino" : 4, "quantity" : 4 }{ "_id" :ObjectId("55a66f3c7db4e9f2ef68107b"), "ino" : 5,"quantity" : 5 }{ "_id" :ObjectId("55a66f3c7db4e9f2ef68107c"), "ino" : 6,"quantity" : 6 }{ "_id" :ObjectId("55a66f3c7db4e9f2ef68107d"), "ino" : 7, "quantity": 7 }{ "_id" :ObjectId("55a66f3c7db4e9f2ef68107e"), "ino" : 8,"quantity" : 8 }{ "_id" :ObjectId("55a66f3c7db4e9f2ef68107f"), "ino" : 9,"quantity" : 9 }{ "_id" :ObjectId("55a66f3c7db4e9f2ef681080"), "ino" : 10,"quantity" : 10 }{ "_id" :ObjectId("55a66f3c7db4e9f2ef681081"), "ino" : 11,"quantity" : 11 }{ "_id" :ObjectId("55a66f3c7db4e9f2ef681082"), "ino" : 12,"quantity" : 12 }{ "_id" :ObjectId("55a66f3c7db4e9f2ef681083"), "ino" : 13,"quantity" : 13 }{ "_id" : ObjectId("55a66f3c7db4e9f2ef681084"),"ino" : 14, "quantity" : 14 }{ "_id" :ObjectId("55a66f3c7db4e9f2ef681085"), "ino" : 15,"quantity" : 15 }{ "_id" :ObjectId("55a66f3c7db4e9f2ef681086"), "ino" : 16,"quantity" : 16 }{ "_id" :ObjectId("55a66f3c7db4e9f2ef681087"), "ino" : 17,"quantity" : 17 }{ "_id" :ObjectId("55a66f3c7db4e9f2ef681088"), "ino" : 18,"quantity" : 18 }{ "_id" :ObjectId("55a66f3c7db4e9f2ef681089"), "ino" : 19,"quantity" : 19 }Type "it" for more> 

We db. collection. when the find () Statement queries a document, it is found that if Mongo shell is not assigned to a variable iteration data using the var keyword, the cursor automatically iterates the results of the first 20 documents and returns them.

After "it" is entered, the last 20 data records are displayed.

 

2. You can use DBQuery. shellbatchsize to change the number of iterations (10 records are displayed on each page)

 

Example:

     >DBQuery.shellBatchSize = 10

 

Now the cursor automatically iterates the results of the first 10 documents and returns

 

3. Define a variable to save the cursor.

 

Example:

      > var cursor=db.items.find()

If you use a variable to save the cursor and do not output data automatically, You need to implement the cursor of the query result for traversal.

 

4. traverse the cursor


    >var cursor=db.items.find()    >while(cursor.hasNext()){       var doc = cursor.next();      printjson(doc);    };

Or

ForEach () loop traversal:

   >cursor.forEach( function(doc) { printjson(doc);});


When you traverse the cursor to the end of the returned batch processing, if more results exist, cursor. next () will execute more operations to obtain the next batch.

The query result returned by the MongoDB server when calling cursor. in hasNext (), the size of a batch of MongoDB files does not exceed the maximum BSON document size. However, for most queries, the first batch of 101 documents or enough files exceed 1 MB, the subsequent batch size is 4 MB. If the first batch is to return 101 documents, execute hasNext when the traversal is complete, it will go to the database query results until all results are returned, the cursor will be closed.

 

You can use the objsleftinbatch () method to view the number or size of documents returned each time, as shown in the following example:

   >var cursor=db.items.find()   >cursor .objsLeftInBatch();


When the query is just executed, the method for executing cursor. objsLeftInBatch () will display 101, which indicates that the first batch of 101 documents are returned (101 documents do not exceed 1 MB)

When we traverse 101 documents, when we execute cursor. hasNext (), will the second batch return the 101 documents?

We first traverse the 101 documents, as shown in the following example:

   >for(vari=0;i<101;i++){      var doc = cursor.next();      printjson(doc);    }


After the first batch of returned results are iterated, We will query the next batch of results in the database when we execute cursor. hasNext ();. The objsLeftInBatch method is used to check the size of the returned documents, as shown in the following example:

   >cursor.hasNext();   >cursor .objsLeftInBatch();

At this time, the returned result is 9899, not 101 documents, but 4 MB. Our 9899 documents do not reach 4 MB, and all of them are returned.

 

Note:

MongoDB uses the memory ing storage engine, which converts disk I/O operations into memory operations. For read operations, the data in the memory serves as a cache. During the query, results are returned in batches. This is a lazy loading process. You can query the next batch of results in the database only when necessary, which saves resources and does not waste resources.

 

Iii. cursor operations

We can also modify the limits, jumps, and sorting order of the returned results at will for the cursor of the document.

 

1. limit

The limit Method limits the number of results returned by the cursor, as shown in the following example:

       >db.items.find().limit(5)

Only 5 documents are returned.

 

2. sort

The sort () method sorts data. It uses 1 or-1 to specify whether the sorting method is ascending or descending Based on the specified field, similar to the SQL order by method.

Example:

          >db.items.find({"ino":{$lt:5}}).sort({"quantity":-1})
 

We query the result where ino is smaller than 5 and sort the result in descending order by the quantity field.


We can specify multiple fields for sorting. For example, we first sort the quantity fields in descending order and then sort them in ascending order by info, as shown in the following example:

         >db.items.find({"ino":{$lt:5}}).sort({"quantity":-1,"info":1})


We query the result where ino is smaller than 5 and sort the result in descending order by the quantity field.

 

We can also combine queries with the limit () method and sort the results.

Example:

        >db.items.find().limit(3).sort({"quantity":1})

 

First, we sort the quantity field in ascending order and return the first three records. We found that the document with no key quantity (that is, the key quantity value is null) is at the top, which is in MongoDB, when comparing different types of BSON values, MongoDB uses the following comparison sequence, from minimum to maximum:

  1. MinKey (internal type)
  2. Null
  3. Numbers (ints, longs, doubles)
  4. Symbol, String
  5. Object
  6. Array
  7. BinData
  8. ObjectId
  9. Boolean
  10. Date
  11. Timestamp
  12. Regular Expression
  13. MaxKey (internal type)


For a query that includes an index-free sorting operation, the server must load all documents to the memory before returning any results for sorting.

3. skip


The skip method can skip the number of entries with the specified value and return the result of the remaining number. It can be combined with the limit () method to achieve paging effect.

Example:

      >db.items.find().skip(10).limit(10)

Skip 10th, return from 11th, and return only 10 documents.

The skip method skips the number of entries and skips one entry. If the set is large (for example, there are many pages), the skip will get slower and slower, and more processors (CPU) are required ), this affects performance.

We can use a key value to compare the order of the page, so that you do not need to use the skip method.

Example:

          >db.items.find({"ino":{$lt:20,$gt:9}}).sort({"info":1})

 

Iv. cursor description

By default, the server will automatically close the cursor that is idle after 10 minutes or the client traverses the final result. You need to manually close the cursor or clear the cursor. You can use the cursor to specify the noTimeout mark in the query. Using cursor. addOption (), you can use the following method:

     >var cursor = db.items.find().addOption(DBQuery.Option.noTimeout);


You can view the cursor information:

(1) Total number of opened cursors

(2) The cursor size used by the current client

(3) number of time-out cursors since the last server restart


We can check the usage of the cursor.


Example:

     >db.serverStatus().metrics.cursor





Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.