MongoDB - Day12 ( Cursor Methods)

Before reading this article, I highly recommend reading the following previous parts of the series:

Cursor Method

MongoDB provides a range of cursor methods. As their names indicate, these methods perform actions for a cursor and return the result. This article explains some important and useful cursor methods, the following cursor methods.

Method Name Description
Count Return total number of document in cursor
Limit Limit the record in cursor
Skip Skip a number of document in cursor
Sort Returns results in ordered form
Next Return next document from cursor
toArray Returns an array that contains all documents returned by the cursor.
Size Returns a count of the documents in the cursor.
hasNext hasNext() method is used to find that cursor contain next(more) document or nor
forEach Apply a JavaScript function for every document in a cursor.
Explain Return information about query execution plan for a cursor

First we create a collection.

db.createCollection("Employee",{capped:false,autoIndexID:false,size:5040320,max:50})

Now insert the following data into the “Employee” collection.

  1. {  
  2.          "_id" : ObjectId("55cc8833211cb7f01f58ce20"),  
  3.          "Name" : "Pankaj Choudhary",  
  4.          "City" : "Alwar",  
  5.          "Salary" : 35000  
  6.  }  
  7.  {  
  8.          "_id" : ObjectId("55cc8850211cb7f01f58ce21"),  
  9.          "Name" : "Sandeep Jangid",  
  10.          "City" : "Jaipur",  
  11.          "Salary" : 25000  
  12.  }  
  13.  {  
  14.          "_id" : ObjectId("55cc8868211cb7f01f58ce22"),  
  15.          "Name" : "Rahul Prajapat",  
  16.          "City" : "Delhi",  
  17.          "Salary" : 27000  
  18.  }  
  19.  {  
  20.          "_id" : ObjectId("55cc887b211cb7f01f58ce23"),  
  21.          "Name" : "Sanjeev Baldia",  
  22.          "City" : "Delhi",  
  23.          "Salary" : 47000  
  24.  }  
  25.  {  
  26.          "_id" : ObjectId("55cc8895211cb7f01f58ce24"),  
  27.          "Name" : "Narendra Sharma",  
  28.          "City" : "Jaipur",  
  29.          "Salary" : 35000  
  30.  }  
  31.  {  
  32.          "_id" : ObjectId("55cc88b0211cb7f01f58ce25"),  
  33.          "Name" : "Omi Choudhary",  
  34.          "City" : "Alwar",  
  35.          "Salary" : 27000  
  36.  }  
  37.  {  
  38.          "_id" : ObjectId("55cc88f5211cb7f01f58ce27"),  
  39.          "Name" : "Nitin Yadav",  
  40.          "City" : "Jaipur",  
  41.          "Salary" : 32000  
  42.  }  
After inserting the preceding data the “Employee” collection looks as in the following.

document

Now we understand each method and use the “Employee” collection in examples.

Count() Method

The Count method returns the numbers of documents present in a cursor or referenced by a cursor. To determine the number of matching documents, Append the count() method to a find() query.

Syntax

db.Collection_Name.find(<query>).count(<applySkipLimit>)

Parameters
 
Name Type Description
Query Document Define selection criteria
applySkipLimit Boolean Optional. Consider the effect of the skip() and limit() method. The value is false by default.

Count All Documents

To count all the documents of a collection use the count() method without using any query parameter in the find() method.

Example

db.Employee.find().count()

This query returns the total number of documents present in the “Employee” collection.

Output

7

The Count method with the Query parameter: to count all the documents that match a specific criteria, use the query parameter in the find method.

Example

db.Employee.find({Salary:{$gt:30000}}).count()

This query returns the count of all employees with a salary greater than 30000.

Output

4

Use Limit with Count method

Use the limit method with the count method to return a total of specific documents. If use the limit method then we must set the value of the applySkipLimit parameter to true.

Example

db.Employee.find({Salary:{$gt:30000}}).limit(2).count()

Output

4

The preceding query returns 4 instead of 2 because we don't set the value of the applySkipLimit parameter to true. Now we set the value applySkipLimit parameter to true and get the desired output.

Example

db.Employee.find({Salary:{$gt:30000}}).limit(2).count(true)

Output

2

Note: the db.collection.find(<query>).count() construct works the same as db.collection.count(<query>).

Example 1

Query: db.Employee.find().count()

Output: 7

Query: db.Employee.count()

Output: 7

Example 2

Query: db.Employee.find({Salary:{$gt:30000}}).count()

Output: 4

Query: db.Employee.count({Salary:{$gt:30000}})

Output: 4

Limit() Method

The Limit method specifies the maximum number of documents the cursor will return. The Limit() method in MongoDB is similar to the limit statement of SQL databases. The limit() method accepts an integer type argument that is the number of documents you want to display. We must be use the Limit() method to prevent MongoDB from returning more results than required for processing. Limit(0) (A limit() value of 0) is equivalent to setting no limit.

Syntax: db.Collection_Name.find(<query>).limit(number)

Parameters

Parameter Type Description
Query Document Specify selection criteria
Number Integer Specify number of documents to display

Limit the Output of Cursor

To retrieve the data in a specific amount, pass the value of the <number> parameter in the limit method.

Example

db.Employee.find().limit(3).pretty()

This query retrieves the top 3 records from the cursor.

Output

  1. {  
  2.          "_id" : ObjectId("55cc8833211cb7f01f58ce20"),  
  3.          "Name" : "Pankaj Choudhary",  
  4.          "City" : "Alwar",  
  5.          "Salary" : 35000  
  6.  }  
  7.  {  
  8.          "_id" : ObjectId("55cc8850211cb7f01f58ce21"),  
  9.          "Name" : "Sandeep Jangid",  
  10.          "City" : "Jaipur",  
  11.          "Salary" : 25000  
  12.  }  
  13.  {  
  14.          "_id" : ObjectId("55cc8868211cb7f01f58ce22"),  
  15.          "Name" : "Rahul Prajapat",  
  16.          "City" : "Delhi",  
  17.          "Salary" : 27000  
  18.  }  
Limit method with query parameter

To retrieve a specific number of documents that match a selection criteria use the <query> parameter in find and <number> parameter in the limit method.

Example

db.Employee.find({City:"Delhi"}).limit(2).pretty()

This query returns the details of the top 2 employees living in the city “Delhi”.

Output

{
   "_id" : ObjectId("55cc8868211cb7f01f58ce22"),
   "Name" : "Rahul Prajapat",
   "City" : "Delhi",
   "Salary" : 27000
}
{
   "_id" : ObjectId("55cc887b211cb7f01f58ce23"),
   "Name" : "Sanjeev Baldia",
   "City" : "Delhi",
   "Salary" : 47000
}


Skip() Method

The Skip() method skips the documents from the result returned by the cursor. In other words, the skip() method controls the MongoDB returning results.

Syntax: db.Collection_Name.find(<query>).skip(number>)

Parameters:
 
Parameter Type Description
Query Document Specify selection criteria
Number Integer Specify number of documents to skip

Start result from a specific Position

We can use the skip() method to start the result from a specific position. If we want to retrieve the result from the third document of the collection then pass 3 as the parameter value in the skip method. The default value of the skip() method is 0. But the skip() method is expensive because it requires the server to start from the beginning of the collection to get the skip position before beginning to return results.

Example

db.Employee.find().skip(3).pretty()

This query skips the first 3 documents from the result and prints the remaining documents.

Output

  1. {  
  2.          "_id" : ObjectId("55cc887b211cb7f01f58ce23"),  
  3.          "Name" : "Sanjeev Baldia",  
  4.          "City" : "Delhi",  
  5.          "Salary" : 47000  
  6.  }  
  7.  {  
  8.          "_id" : ObjectId("55cc8895211cb7f01f58ce24"),  
  9.          "Name" : "Narendra Sharma",  
  10.          "City" : "Jaipur",  
  11.          "Salary" : 35000  
  12.  }  
  13.  {  
  14.          "_id" : ObjectId("55cc88b0211cb7f01f58ce25"),  
  15.          "Name" : "Omi Choudhary",  
  16.          "City" : "Alwar",  
  17.          "Salary" : 27000  
  18.  }  
  19.  {  
  20.          "_id" : ObjectId("55cc88f5211cb7f01f58ce27"),  
  21.          "Name" : "Nitin Yadav",  
  22.          "City" : "Jaipur",  
  23.          "Salary" : 32000  
  24.  }  
Use the skip() method with a limit

We can also use the skip() method with limit(). This time the skip() method removes the starting documents from the cursor and returns documents depending on the value of the <number> parameter of the limit() method.

Example

db.Employee.find().limit(2).skip(1).pretty()

This query skips the first document and returns the next two documents from the cursor.

Output

{
   "_id" : ObjectId("55cc8850211cb7f01f58ce21"),
   "Name" : "Sandeep Jangid",
   "City" : "Jaipur",
   "Salary" : 25000
}
{
   "_id" : ObjectId("55cc8868211cb7f01f58ce22"),
   "Name" : "Rahul Prajapat",
   "City" : "Delhi",
   "Salary" : 27000
}


Sort() Method

The sort() method retrieves the result in a specific order. The sorting may be done either by a single field or multiple fields. We must use the sort() method to the cursor before retrieving any documents from the database. MongoDB does not guarantee the order of query results. MongoDB uses a top-k sort algorithm. This algorithm buffers either the first k results or the last k results, depending on the sort order.

Syntax: db.Collection_Name.find(<query>).sort(<sort>)

Parameters
 
Parameter Type Description
Query Document Specify selection criteria
Sort Document Defines the sort order of the result set.

Syntax of sort Parameter

The sort parameter contains field and value pairs as follows.

Syntax: { field:sorting_order)

Sorting_Order

Value Description
1 Sort in ascending order
-1 Sort in descending order

When the sort() method compares various types of data, use the following comparison order.

Type Order
MinKey 1
Null 2
Numbers(int,double) 3
Symbol , String 4
Object 5
Array 6
BinData 7
ObjectId 8
Boolean 9
Date 10
Timestamp 11
Regular Expression 12
MaxKey 13

Important about sorting order:

  • MongoDB treats { } (not exsting) and “null” as the same
  • In ascending order, the sort() method compares the smallest element of arrays
  • In descending order, the sort() method largest element of the arrays.
  • Sorting priority of empty array is less than null or a not existing field.

Now we consider some examples.

Sort Result according fields

To sort the retrieving result according any field pass the name of that field any sorting order.

1. Sort Result according single field

Example

db.Employee.find().sort({"Salary":1}).pretty()

This query sorts the result by the “Salary” field in ascending order.

Output

  1. {  
  2.          "_id" : ObjectId("55cc8850211cb7f01f58ce21"),  
  3.          "Name" : "Sandeep Jangid",  
  4.          "City" : "Jaipur",  
  5.          "Salary" : 25000  
  6.  }  
  7.  {  
  8.          "_id" : ObjectId("55cc8868211cb7f01f58ce22"),  
  9.          "Name" : "Rahul Prajapat",  
  10.          "City" : "Delhi",  
  11.          "Salary" : 27000  
  12.  }  
  13.  {  
  14.          "_id" : ObjectId("55cc88b0211cb7f01f58ce25"),  
  15.          "Name" : "Omi Choudhary",  
  16.          "City" : "Alwar",  
  17.          "Salary" : 27000  
  18.  }  
  19.  {  
  20.          "_id" : ObjectId("55cc88f5211cb7f01f58ce27"),  
  21.          "Name" : "Nitin Yadav",  
  22.          "City" : "Jaipur",  
  23.          "Salary" : 32000  
  24.  }  
  25.  {  
  26.          "_id" : ObjectId("55cc8833211cb7f01f58ce20"),  
  27.          "Name" : "Pankaj Choudhary",  
  28.          "City" : "Alwar",  
  29.          "Salary" : 35000  
  30.  }  
  31.  {  
  32.          "_id" : ObjectId("55cc8895211cb7f01f58ce24"),  
  33.          "Name" : "Narendra Sharma",  
  34.          "City" : "Jaipur",  
  35.          "Salary" : 35000  
  36.  }  
  37.  {  
  38.          "_id" : ObjectId("55cc887b211cb7f01f58ce23"),  
  39.          "Name" : "Sanjeev Baldia",  
  40.          "City" : "Delhi",  
  41.          "Salary" : 47000  
  42.  }  
2. Sort Result according multiple fields

Example

db.Employee.find().sort({"Salary":1,"City":-1}).pretty()

This query sort result is first by the “Salary” field in ascending order and within each “Salary” field the sort is by the “City” field in descending order.

Output
  1. {  
  2.      "_id" : ObjectId("55cc8850211cb7f01f58ce21"),  
  3.      "Name" : "Sandeep Jangid",  
  4.      "City" : "Jaipur",  
  5.      "Salary" : 25000  
  6.  }  
  7.  {  
  8.      "_id" : ObjectId("55cc8868211cb7f01f58ce22"),  
  9.      "Name" : "Rahul Prajapat",  
  10.      "City" : "Delhi",  
  11.      "Salary" : 27000  
  12.  }  
  13.  {  
  14.      "_id" : ObjectId("55cc88b0211cb7f01f58ce25"),  
  15.      "Name" : "Omi Choudhary",  
  16.      "City" : "Alwar",  
  17.      "Salary" : 27000  
  18.  }  
  19.  {  
  20.      "_id" : ObjectId("55cc88f5211cb7f01f58ce27"),  
  21.      "Name" : "Nitin Yadav",  
  22.      "City" : "Jaipur",  
  23.      "Salary" : 32000  
  24.  }  
  25.  {  
  26.      "_id" : ObjectId("55cc8895211cb7f01f58ce24"),  
  27.      "Name" : "Narendra Sharma",  
  28.      "City" : "Jaipur",  
  29.      "Salary" : 35000  
  30.  }  
  31.  {  
  32.      "_id" : ObjectId("55cc8833211cb7f01f58ce20"),  
  33.      "Name" : "Pankaj Choudhary",  
  34.      "City" : "Alwar",  
  35.      "Salary" : 35000  
  36.  }  
  37.  {  
  38.      "_id" : ObjectId("55cc887b211cb7f01f58ce23"),  
  39.      "Name" : "Sanjeev Baldia",  
  40.      "City" : "Delhi",  
  41.      "Salary" : 47000  
Use limit and Projection with Sort() Method

We can use projection (return specific field) and limit with the sort() method.

Example

db.Employee.find({},{_id:0,Name:1,Salary:1}).sort({City:1}).limit(4).pretty()

This query is executed in as in the following procedure:
  1. Sort the documents by the “City” field in ascending order.
  2. Now select the top 4 results.
  3. Return the “Name” and “Salary” fields of the selected documents.

Output

{ "Name" : "Pankaj Choudhary", "Salary" : 35000 }
{ "Name" : "Omi Choudhary", "Salary" : 27000 }
{ "Name" : "Rahul Prajapat", "Salary" : 27000 }
{ "Name" : "Sanjeev Baldia", "Salary" : 47000 }


Natural Sort

MongoDB provides a “$natural” parameter in the sort() method to return items depending on their natural order within the database.

Here natural order is the insertion order of the documents.

Example 1

db.Employee.find({},{_id:0,Name:1,Salary:1,City:1}).sort({$natural:1}).pretty()

This query returns the documents according to their insertion order from the “Oldest” to the “Newest” entered documents.

Output

{ "Name" : "Pankaj Choudhary", "City" : "Alwar", "Salary" : 35000 }
{ "Name" : "Sandeep Jangid", "City" : "Jaipur", "Salary" : 25000 }
{ "Name" : "Rahul Prajapat", "City" : "Delhi", "Salary" : 27000 }
{ "Name" : "Sanjeev Baldia", "City" : "Delhi", "Salary" : 47000 }
{ "Name" : "Narendra Sharma", "City" : "Jaipur", "Salary" : 35000 }
{ "Name" : "Omi Choudhary", "City" : "Alwar", "Salary" : 27000 }
{ "Name" : "Nitin Yadav", "City" : "Jaipur", "Salary" : 32000 }

Example 2

db.Employee.find({},{_id:0,Name:1,Salary:1,City:1}).sort({$natural:-1}).pretty()

This query returns the documents by their insertion order from the “Newest” to the “Oldest” entered documents.

Output

{ "Name" : "Nitin Yadav", "City" : "Jaipur", "Salary" : 32000 }
{ "Name" : "Omi Choudhary", "City" : "Alwar", "Salary" : 27000 }
{ "Name" : "Narendra Sharma", "City" : "Jaipur", "Salary" : 35000 }
{ "Name" : "Sanjeev Baldia", "City" : "Delhi", "Salary" : 47000 }
{ "Name" : "Rahul Prajapat", "City" : "Delhi", "Salary" : 27000 }
{ "Name" : "Sandeep Jangid", "City" : "Jaipur", "Salary" : 25000 }
{ "Name" : "Pankaj Choudhary", "City" : "Alwar", "Salary" : 35000 }

Next() Method

The Next() method retrieves the next document from the cursor. The Next() method returns null if the cursor doesn't contain more documents.

Syntax: Cursor_objectName.next()

Note: cursor_objectName is the object containing a reference returned by the “db.collection.find()” method.

Example

Query 1: var Cursor1=db.Employee.find()

In this query we assign the reference into the Cursor1 object returned by the find() method.

Query 2: Cursor1.next()

This query returns the first document from the cursor object.

Output

{
   "_id" : ObjectId("55cc8833211cb7f01f58ce20"),
   "Name" : "Pankaj Choudhary",
   "City" : "Alwar",
   "Salary" : 35000
}


Query 3

Cursor1.next()

This query returns the next (second) document from the cursor object.

Output

{
   "_id" : ObjectId("55cc8850211cb7f01f58ce21"),
   "Name" : "Sandeep Jangid",
   "City" : "Jaipur",
   "Salary" : 25000
}


We can see the preceding queries in the following image.

output

toArray() Method

The toArray() method returns an array containing all the documents from a cursor and iterates the cursor completely. The toArray() method loads all the documents into memory from the cursor and exhausts the cursor.

Syntax: db.Collection_Name.find().toArray()

Retrieve all documents from cursor

To retrieve all documents from a cursor use the toArray() method with the cursor.

Example

db.Employee.find({},{_id:0,Name:1,Salary:1}).toArray()

Output

  1. [  
  2.      {  
  3.              "Name" : "Pankaj Choudhary",  
  4.              "Salary" : 35000  
  5.      },  
  6.      {  
  7.              "Name" : "Sandeep Jangid",  
  8.              "Salary" : 25000  
  9.      },  
  10.      {  
  11.              "Name" : "Rahul Prajapat",  
  12.              "Salary" : 27000  
  13.      },  
  14.      {  
  15.              "Name" : "Sanjeev Baldia",  
  16.              "Salary" : 47000  
  17.      },  
  18.      {  
  19.              "Name" : "Narendra Sharma",  
  20.              "Salary" : 35000  
  21.      },  
  22.      {  
  23.              "Name" : "Omi Choudhary",  
  24.              "Salary" : 27000  
  25.      },  
  26.      {  
  27.              "Name" : "Nitin Yadav",  
  28.              "Salary" : 32000  
  29.      }  
  30.  ]  
Use Array variable

We can store the result into an array variable retrieved from the toArray() method. This approach provides an option to retrieve a specific document from an array variable.

Example
  1. var Array_=db.Employee.find({},{_id:0,Name:1,Salary:1}).toArray()  
  2. if(Array_.length>0)  
  3. {  
  4.    Array_   
  5. }  
Output
  1. [  
  2.      {  
  3.              "Name" : "Pankaj Choudhary",  
  4.              "Salary" : 35000  
  5.      },  
  6.      {  
  7.              "Name" : "Sandeep Jangid",  
  8.              "Salary" : 25000  
  9.      },  
  10.      {  
  11.              "Name" : "Rahul Prajapat",  
  12.              "Salary" : 27000  
  13.      },  
  14.      {  
  15.              "Name" : "Sanjeev Baldia",  
  16.              "Salary" : 47000  
  17.      },  
  18.      {  
  19.              "Name" : "Narendra Sharma",  
  20.              "Salary" : 35000  
  21.      },  
  22.      {  
  23.              "Name" : "Omi Choudhary",  
  24.              "Salary" : 27000  
  25.      },  
  26.      {  
  27.              "Name" : "Nitin Yadav",  
  28.              "Salary" : 32000  
  29.      }  
  30.  ]  
We can also return a specific document from an Array variable.

Example
  1. var Array_=db.Employee.find({},{_id:0,Name:1,Salary:1}).limit(3).toArray()  
  2.   
  3. if(Array_.length>0)  
  4. {  
  5.    printjson(Array_[1])  
  6. }  
The preceding query returns the second document from an Array_ variable.

Output

{ "Name" : "Sandeep Jangid", "Salary" : 25000 }


Difference b/w db.collection.find() and db.collection.find().toArray() methods

The “DBQuery.shellBatchSize” command specifies the number of documents to be visible at a time. We can use the “it” command to continue to iterate the cursor. By default the value of “DBQuery.shellBatchSize” is 20. That means MongoDb shows 20 records at a time. The number of records that will be shown by the find() method depends upon the value of “DBQuery.shellBatchSize”. In other words, if the value of “DBQuery.shellBatchSize” is equal 10 then find() shows only 10 documents at a time, we must use the “it” command to display the next 10 documents.

But there is no effect on the value of “DBQuery.shellBatchSize” upon the toArray() method, this method shows all the documents in a single batch.

Example

DBQuery.shellBatchSize =4

In this command we set the value of “DBQuery.shellBatchSize” to 4. This means the cursor shows only 4 documents at a time.

db.Employee.find({},{_id:0,Name:1})

Output

{ "Name" : "Pankaj Choudhary" }
{ "Name" : "Sandeep Jangid" }
{ "Name" : "Rahul Prajapat" }
{ "Name" : "Sanjeev Baldia" }


Type "it" for more it:

{ "Name" : "Narendra Sharma" }
{ "Name" : "Omi Choudhary" }
{ "Name" : "Nitin Yadav" }


In the preceding example we can see that the cursor prints only 4 documents at a time. To iterate the cursor we use the “it” command. But the toArray() method will show all the documents in a single batch.
Let's see an example.

db.Employee.find({},{_id:0,Name:1}).toArray()

Output
  1. [  
  2.     {  
  3.             "Name" : "Pankaj Choudhary"  
  4.     },  
  5.     {  
  6.             "Name" : "Sandeep Jangid"  
  7.     },  
  8.     {  
  9.             "Name" : "Rahul Prajapat"  
  10.     },  
  11.     {  
  12.             "Name" : "Sanjeev Baldia"  
  13.     },  
  14.     {  
  15.             "Name" : "Narendra Sharma"  
  16.     },  
  17.     {  
  18.             "Name" : "Omi Choudhary"  
  19.     },  
  20.     {  
  21.             "Name" : "Nitin Yadav"  
  22.     }  
  23. ]  
Size() method

The Size() method returns the number of documents that match the selection criteria of the find() method after applying any skip() and limit() methods.

Syntax: db.collection_name.find().count()

Count all documents

To count all the documents of a collection use the size() method with the cursor.

Example

db.Employee.find({},{_id:0,Name:1}).size()

Output: 7

limit Method

To count a limited number of documents use the size() method with the limit() method.

Example

db.Employee.find({},{_id:0,Name:1}).limit(4).size()

Output: 4

skip() Method

db.Employee.find({Salary:{$gt:25000}}).skip(3).size()

Output: 3

size() method with skip() and limit() methods

db.Employee.find({Salary:{$gt:25000}}).limit(2).skip(1).size()

Output: 2

hasNext() method

The hasNext() method finds the cursor containing the next (more) documents. The hasNext() method returns “true” if further iteration of the cursor is possible otherwise it returns “false”.

Syntax: db.Collection_Came.find().hasNext()

Example 1

var nxt=db.Employee.find().limit(2)

var value=nxt.hasNext()?"Cursor conatin more document":"Cursor doesn't contain more document
"
if(value){ printjson(value) }


Output

"Cursor conatin more document"

Example 2

var nxt=db.Employee.find().limit(2)
var value=nxt.hasNext()?nxt.next():null
if(value){ printjson(value) }


Output

{
   "_id" : ObjectId("55cc8833211cb7f01f58ce20"),
   "Name" : "Pankaj Choudhary",
   "City" : "Alwar",
   "Salary" : 35000
}

If the cursor doesn't contain another document and often that we use the next() method for a cursor then MongoDB will throw an error as in the following.

2015-08-14T18:50:24.896+0530 E QUERY Error: error hasNext: false:

    at Error (<anonymous>)
    at DBQuery.next (src/mongo/shell/query.js:255:15)
    at (shell):1:5 at src/mongo/shell/query.js:255

forEach() method

We can use a forEach loop with a cursor variable to iterate the cursor and access the documents. The forEach method iterates the cursor to apply a JavaScript function to each document from the cursor.

Syntax: db.Collection_Name.find(<query>).forEach(<function>)

Parameters

Parameter Type Description
Query Document Specify selection criteria
Function JavaScript A JavaScript function to apply to each document from the cursor

Example

db.Employee.find().forEach(function(Employee){ var detail= "Employee Name="+Employee.Name +"
Employee Salary=" +Employee.Salary; print(detail );})


Output:

Employee Name=Pankaj Choudhary Employee Salary=35000
Employee Name=Sandeep Jangid Employee Salary=25000
Employee Name=Rahul Prajapat Employee Salary=27000
Employee Name=Sanjeev Baldia Employee Salary=47000
Employee Name=Narendra Sharma Employee Salary=35000
Employee Name=Omi Choudhary Employee Salary=27000
Employee Name=Nitin Yadav Employee Salary=32000


Explain() Method

The Explain() method returns the query plan for the db.collection.find() method. The amount of information returned by the explain() method depends on the verbosity mode. The cursor.explain() method returns queryPlanner and executionStats.

Syntax: db.collectin_name.find().explain(verbosity)

Parameter

Parameter Type Description
Verbosity String Optional. Specifies the verbosity mode for the explain method. This method specifies the verbosity mode for the explain.

Verbosity mode has the following 3 possibilities:

  1. queryPlanner
  2. executionStats
  3. allPlansExecution

The default mode for verbosity is queryPlanner.

Exaplain() method with queryPlanner Mode

MongoDB runs the query optimizer to choose a plan and returns the queryPlanner information for the evaluated method.

Example

db.Employee.find().explain("queryPlanner")

Output

  1. {  
  2.      "queryPlanner" : {  
  3.              "plannerVersion" : 1,  
  4.              "namespace" : "Temp.Employee",  
  5.              "indexFilterSet" : false,  
  6.              "parsedQuery" : {  
  7.                      "$and" : [ ]  
  8.              },  
  9.              "winningPlan" : {  
  10.                      "stage" : "COLLSCAN",  
  11.                      "filter" : {  
  12.                              "$and" : [ ]  
  13.                      },  
  14.                      "direction" : "forward"  
  15.              },  
  16.              "rejectedPlans" : [ ]  
  17.      },  
  18.      "serverInfo" : {  
  19.              "host" : "Your host name",  
  20.              "port" : 27017,  
  21.              "version" : "3.0.3",  
  22.              "gitVersion" : "b40106b36eecd1b4407eb1ad1af6bc60593c6105"  
  23.      },  
  24.      "ok" : 1  
  25.  }  
Exaplain() method with executionStatsMode

MongoDB runs the query optimizer to choose a plan and returns statistics describing the execution of the winning plan.

Example

db.Employee.find().explain("executionStats")

Output
  1. {  
  2.          "queryPlanner" : {  
  3.                  "plannerVersion" : 1,  
  4.                  "namespace" : "Temp.Employee",  
  5.                  "indexFilterSet" : false,  
  6.                  "parsedQuery" : {  
  7.                          "$and" : [ ]  
  8.                  },  
  9.                  "winningPlan" : {  
  10.                          "stage" : "COLLSCAN",  
  11.                          "filter" : {  
  12.                                  "$and" : [ ]  
  13.                          },  
  14.                          "direction" : "forward"  
  15.                  },  
  16.                  "rejectedPlans" : [ ]  
  17.          },  
  18.          "executionStats" : {  
  19.                  "executionSuccess" : true,  
  20.                  "nReturned" : 7,  
  21.                  "executionTimeMillis" : 0,  
  22.                  "totalKeysExamined" : 0,  
  23.                  "totalDocsExamined" : 7,  
  24.                  "executionStages" : {  
  25.                          "stage" : "COLLSCAN",  
  26.                          "filter" : {  
  27.                                  "$and" : [ ]  
  28.                          },  
  29.                          "nReturned" : 7,  
  30.                          "executionTimeMillisEstimate" : 0,  
  31.                          "works" : 9,  
  32.                          "advanced" : 7,  
  33.                          "needTime" : 1,  
  34.                          "needFetch" : 0,  
  35.                          "saveState" : 0,  
  36.                          "restoreState" : 0,  
  37.                          "isEOF" : 1,  
  38.                          "invalidates" : 0,  
  39.                          "direction" : "forward",  
  40.                          "docsExamined" : 7  
  41.                  }  
  42.   
  43. },  
  44.          "serverInfo" : {  
  45.                  "host" : "Your Host Name",  
  46.                  "port" : 27017,  
  47.                  "version" : "3.0.3",  
  48.                  "gitVersion" : "b40106b36eecd1b4407eb1ad1af6bc60593c6105"  
  49.          },  
  50.          "ok" : 1  
  51.  }  
Exaplain() method with allPlansExecution

MongoDB runs the query optimizer to choose the winning plan and returns statistics describing the execution of the winning plan and also retuns statistics for the other candidate plans captured during plan selection.

Example

db.Employee.find().explain("allPlansExecution")

Output
  1. {  
  2.      "queryPlanner" : {  
  3.              "plannerVersion" : 1,  
  4.              "namespace" : "Temp.Employee",  
  5.              "indexFilterSet" : false,  
  6.              "parsedQuery" : {  
  7.                      "$and" : [ ]  
  8.              },  
  9.              "winningPlan" : {  
  10.                      "stage" : "COLLSCAN",  
  11.                      "filter" : {  
  12.                              "$and" : [ ]  
  13.                      },  
  14.                      "direction" : "forward"  
  15.              },  
  16.              "rejectedPlans" : [ ]  
  17.      },  
  18.      "executionStats" : {  
  19.              "executionSuccess" : true,  
  20.              "nReturned" : 7,  
  21.              "executionTimeMillis" : 0,  
  22.              "totalKeysExamined" : 0,  
  23.              "totalDocsExamined" : 7,  
  24.              "executionStages" : {  
  25.                      "stage" : "COLLSCAN",  
  26.                      "filter" : {  
  27.                              "$and" : [ ]  
  28.                      },  
  29.                      "nReturned" : 7,  
  30.                      "executionTimeMillisEstimate" : 0,  
  31.                      "works" : 9,  
  32.                      "advanced" : 7,  
  33.                      "needTime" : 1,  
  34.                      "needFetch" : 0,  
  35.                      "saveState" : 0,  
  36.                      "restoreState" : 0,  
  37.                      "isEOF" : 1,  
  38.                      "invalidates" : 0,  
  39.                      "direction" : "forward",  
  40.                      "docsExamined" : 7  
  41.              },  
  42. "allPlansExecution" : [ ]  
  43.      },  
  44.      "serverInfo" : {  
  45.              "host" : "Your Host Name",  
  46.              "port" : 27017,  
  47.              "version" : "3.0.3",  
  48.              "gitVersion" : "b40106b36eecd1b4407eb1ad1af6bc60593c6105"  
  49.      },  
  50.      "ok" : 1  
  51.  }  
Today we learn some cursor methods. I didn't explain all the cursor methods today, in other words some cursor methods remain to be explained. But we can't understand these methods now because before understanding them we must have some basic knowledge about indexing. So in the next article I will explain “indexing” in MongoDB. Then we will complete the remaining cursor methods.

Thanks for readinig this article.