Search This Blog

Tuesday, December 24, 2013

Cursors in MongoDB and mongo shell Javascrip API

test Important note: This article is in relation to online MongoDB course. For more information about the course and other posts describing its content please check my main page here: M101P: MongoDB for Developers course

The mongo shell support cursors. There are many functions available with this object.
 
> mycursor = db.grades.find(); null

> mycursor.
mycursor.addOption(             mycursor.forEach(               mycursor.max(                   mycursor.showDiskLoc(
mycursor.arrayAccess(           mycursor.hasNext(               mycursor.min(                   mycursor.size(
mycursor.batchSize(             mycursor.hasOwnProperty(        mycursor.next(                  mycursor.skip(
mycursor.clone(                 mycursor.help(                  mycursor.objsLeftInBatch(       mycursor.snapshot(
mycursor.comment(               mycursor.hint(                  mycursor.pretty(                mycursor.sort(
mycursor.constructor            mycursor.itcount(               mycursor.propertyIsEnumerable(  mycursor.toArray(
mycursor.count(                 mycursor.length(                mycursor.readOnly(              mycursor.toLocaleString(
mycursor.countReturn(           mycursor.limit(                 mycursor.readPref(              mycursor.toString(
mycursor.explain(               mycursor.map(                   mycursor.shellPrint(            mycursor.valueOf(

> mycursor.hasNext()
true

By using the mongo shell flexibility you can run JavaScript code. The simple program below retrieves and prints values from the collection as demonstration:
 
> for ( var i =1 ; i<5 && mycursor.hasNext(); i++ ) { print("for iteration # " + i); printjson(mycursor.next()) }
for iteration # 1
{
        "_id" : ObjectId("50906d7fa3c412bb040eb5b4"),
        "student_id" : 15,
        "type" : "quiz",
        "score" : 33.87245622400884
}
for iteration # 2
{
        "_id" : ObjectId("50906d7fa3c412bb040eb5b5"),
        "student_id" : 15,
        "type" : "homework",
        "score" : 18.41724574382455
}
for iteration # 3
{
        "_id" : ObjectId("50906d7fa3c412bb040eb5b6"),
        "student_id" : 15,
        "type" : "homework",
        "score" : 7.475648374118382
}
for iteration # 4
{
        "_id" : ObjectId("50906d7fa3c412bb040eb5b7"),
        "student_id" : 16,
        "type" : "exam",
        "score" : 40.92812784954744
}

There is a way to limit the number or documents to read as well.
 
> mycursor = db.grades.find(); null
null
> mycursor.limit(5); null
null
> while ( mycursor.hasNext()) { printjson(mycursor.next()) }

We can apply a sort function to the cursor as well. The code shows how to list documents in the revers order.
 
> mycursor = db.grades.find(); null
null
> mycursor.limit(5); null
null
> mycursor.sort( { student_id : -1 } )
{ "_id" : ObjectId("50906d7fa3c412bb040eb893"), "student_id" : 199, "type" : "exam", "score" : 67.33828604577803 }
{ "_id" : ObjectId("50906d7fa3c412bb040eb894"), "student_id" : 199, "type" : "quiz", "score" : 48.15737364405101 }
{ "_id" : ObjectId("50906d7fa3c412bb040eb895"), "student_id" : 199, "type" : "homework", "score" : 49.34223066136407 }
{ "_id" : ObjectId("50906d7fa3c412bb040eb896"), "student_id" : 199, "type" : "homework", "score" : 58.09608083191365 }
{ "_id" : ObjectId("50906d7fa3c412bb040eb88f"), "student_id" : 198, "type" : "exam", "score" : 49.65504121659061 }

In the code above this is happening:
  • Create a cursor - no data has been received from the db at this time; merely we have established a db connection with the collection.
  • We say we want to see only 5 documents.
  • When we execute the sort method it fetches data from db, iterates over the cursor and print 5 documents (notice the missing null at the end)
And even further we can concatenate the two functions together on a single line.
 
> mycursor.sort( { student_id : -1 } ).limit(5)
{ "_id" : ObjectId("50906d7fa3c412bb040eb893"), "student_id" : 199, "type" : "exam", "score" : 67.33828604577803 }
{ "_id" : ObjectId("50906d7fa3c412bb040eb894"), "student_id" : 199, "type" : "quiz", "score" : 48.15737364405101 }
{ "_id" : ObjectId("50906d7fa3c412bb040eb895"), "student_id" : 199, "type" : "homework", "score" : 49.34223066136407 }
{ "_id" : ObjectId("50906d7fa3c412bb040eb896"), "student_id" : 199, "type" : "homework", "score" : 58.09608083191365 }
{ "_id" : ObjectId("50906d7fa3c412bb040eb88f"), "student_id" : 198, "type" : "exam", "score" : 49.65504121659061 }

The take away from this is examples is to note that all the function applied to the cursor are not processed on the client site by the mango shell but instead these are instruction sent to the MongoDB engine once the cursor is created and being processed by the engine once the cursor request data to be returned.

The cursor is an interface to sent the parameters to the db engine and to read the returned data.

1 comment:

  1. Are you trying to earn cash from your visitors using popup ads?
    In case you do, have you ever consider using Clickadu?

    ReplyDelete