Thursday 19 September 2019

MongoDB Cursor with Examples

MongoDB Cursor with Examples



Question: What is cursor in MongoDB?
Cursor is a pointer to the result set of a query.
When you run a query for documents we retrieve a pointer (cursor) to the results instead of all result return.


Question: Give example of Cursor?
var myCursor=db.users.find({"age":30});
while (myCursor.hasNext()) {
   print(tojson(myCursor.next()));
}




Question: How to get the data type of variable?
var data=10;
typeof data;

var data='10';
typeof data;

Output
number
string



Question: What is use of forEach with Cursor?
Iterates the cursor to each document.
Example 1
db.users.find({"age":30}).forEach(printjson);

Example 2
db.users.find({"age":30}).forEach(function(data){
    print(data.name);
});
Output
name1
name2
name3



Question: How to use limit with Query?
 
db.users.find({"age":30}).limit(5).pretty();
Now, cursor will return maximum 5 records.


Question: How to get results in Array instead of JSON?
 
db.users.find({"age":30}).toArray()



Question: How to get number of results from Query?
 
db.users.find({"age":30}).size(); //2



Question: How to sort records by name in Ascending order?
 
 db.users.find({"age":30}).sort({"name":1}).forEach(function(data){print(data.name);});



Question: How to sort records by name in Descending order?
 
 db.users.find({"age":30}).sort({"name":-1}).forEach(function(data){print(data.name);});



Question: How to skip 4th record from query?
 
 db.users.find({"age":30}).skip(4).forEach(function(data){print(data.name);});



Question: How to search records with indexing?
 
 db.users.find({"age":30}).hint({"age":1}).pretty();