Skip to content

Retrieving data with find()

Solimando Damien edited this page Jul 6, 2015 · 16 revisions

In Hot, the db.collection.find() method retrieves documents from a table/collection. It returns a cursor to the retrieved data.

The cursor object has the following methods

  • count()
  • limit()
  • skip()
  • sort()
  • promise()

For a detailed description, please read the excellent MongoDB doc

In order to effectively request the database, the promise() method must be called on the cursor object. This will trigger the DB request in a non blocking manner and return a Promise object.

Examples (in Groovy)
db.owners.find().promise()          

Return a promise for all the data of the 'owners' table

db.owners.find([id:6]).promise()

Return a promise for owner having id equal to 6

db.owners.find([name:'John']).promise()

Return a promise for owners having 'John' as name

db.owners.find([name:'John'])
         .sort([id:-1])
         .promise()

Return a promise for owners having 'John' as name and sort results descending

db.owners.find([name:'John'])
         .sort([id:-1])
         .limit(4)
         .promise()

Return a promise for owners having 'John' as name and sort results descending and limit the number of results to 4

db.owners.find([name:'John'])
         .sort([id:-1])
         .limit(4)
         .skip(2)
         .promise()

Return a promise for owners having 'John' as name and sort results descending and limit the number of results to 4 and skip the first twos

Handling the promise

Like explained in Hot promises, the Promise object implements the done(),fail(),then() methods.

In order to handle the query results, just pass a callback to either the done() or the then() methods.

Example
db.owners.find([name:'John']).promise().done { results ->
  print results.size()       // Number of results
  print results[0].name      // John
}

The promise callback argument

The { results -> } callback receives a List/Array/list depending of the used programming language (Groovy/Javascript/Python). That list contains the query results as Map/Object/Dictionary objects. Each object is mapped to a DB row in SGBD systems or a mongodb document.

Example

Given the following table:

id name age
1 Peter 22
2 Ian 23
Groovy
db.crew.find().promise().done { crew ->
  crew.each {              // Iterate to rown results
    println it.name        // Peter, Ian
    println it.age         // 22,23
  }
}
Javascript
db.crew.find().promise().done (function(crew) { 
  crew.forEach(function(it) {       // Iterate to row results
    hprint(it.name)                 // Peter, Ian
    hprint(it.age)                  // 22,23
  })
})
Python
def handleResults(crew):
  for people in crew:        # Iterate to rows
     print people.name       # Peter, Ian
     print people.age        # 22,23

db.crew.find().promise().done(handleResults)

Clone this wiki locally