com.mongodb
Class DBCursor

java.lang.Object
  extended by com.mongodb.DBCursor
All Implemented Interfaces:
Iterable<DBObject>, Iterator<DBObject>

public class DBCursor
extends Object
implements Iterator<DBObject>, Iterable<DBObject>

An iterator over database results. Doing a find() query on a collection returns a DBCursor thus

 DBCursor cursor = collection.find( query );
 if( cursor.hasNext() )
     DBObject obj = cursor.next();
 

Warning: Calling toArray or length on a DBCursor will irrevocably turn it into an array. This means that, if the cursor was iterating over ten million results (which it was lazily fetching from the database), suddenly there will be a ten-million element array in memory. Before converting to an array, make sure that there are a reasonable number of results using skip() and limit().

For example, to get an array of the 1000-1100th elements of a cursor, use

 List obj = collection.find( query ).skip( 1000 ).limit( 100 ).toArray();
 


MongoDB Doc Links

Constructor Summary
DBCursor(DBCollection collection, DBObject q, DBObject k)
          Initializes a new database cursor
 
Method Summary
 DBCursor addOption(int option)
          adds a query option - see Bytes.QUERYOPTION_* for list
 DBCursor addSpecial(String name, Object o)
          adds a special operator like $maxScan or $returnKey e.g.
 DBCursor batchSize(int n)
          Limits the number of elements returned in one batch.
 void close()
          kills the current cursor on the server.
 DBCursor copy()
          Creates a copy of an existing database cursor.
 int count()
          Counts the number of objects matching the query This does not take limit/skip into consideration
 DBObject curr()
          Returns the element the cursor is at.
 DBObject explain()
          Returns an object containing basic information about the execution of the query that created this cursor This creates a DBObject with the key/value pairs: "cursor" : cursor type "nScanned" : number of records examined by the database for this query "n" : the number of records that the database returned "millis" : how long it took the database to execute the query
 DBCollection getCollection()
          gets the collection
 long getCursorId()
          gets the cursor id.
 DBObject getKeysWanted()
          gets the fields to be returned
 int getOptions()
          gets the query options
 DBObject getQuery()
          gets the query
 ServerAddress getServerAddress()
          Gets the Server Address of the server that data is pulled from.
 List<Integer> getSizes()
          gets a list containing the number of items received in each batch
 boolean hasNext()
          Checks if there is another object available
 DBCursor hint(DBObject indexKeys)
          Informs the database of indexed fields of the collection in order to improve performance.
 DBCursor hint(String indexName)
          Informs the database of an indexed field of the collection in order to improve performance.
 int itcount()
          for testing only! Iterates cursor and counts objects
 Iterator<DBObject> iterator()
          creates a copy of this cursor object that can be iterated.
 int length()
          pulls back all items into an array and returns the number of objects.
 DBCursor limit(int n)
          Limits the number of elements returned.
 DBObject next()
          Returns the object the cursor is at and moves the cursor ahead by one.
 int numGetMores()
          gets the number of times, so far, that the cursor retrieved a batch from the database
 int numSeen()
          Returns the number of objects through which the cursor has iterated.
 void remove()
          Not implemented.
 void resetOptions()
          resets the query options
 void setOptions(int options)
          sets the query option - see Bytes.QUERYOPTION_* for list
 int size()
          Counts the number of objects matching the query this does take limit/skip into consideration
 DBCursor skip(int n)
          Discards a given number of elements at the beginning of the cursor.
 DBCursor slaveOk()
          makes this query ok to run on a slave node
 DBCursor snapshot()
          Use snapshot mode for the query.
 DBCursor sort(DBObject orderBy)
          Sorts this cursor's elements.
 List<DBObject> toArray()
          Converts this cursor to an array.
 List<DBObject> toArray(int max)
          Converts this cursor to an array.
 String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

DBCursor

public DBCursor(DBCollection collection,
                DBObject q,
                DBObject k)
Initializes a new database cursor

Parameters:
collection - collection to use
q - query to perform
k - keys to return from the query
Method Detail

copy

public DBCursor copy()
Creates a copy of an existing database cursor. The new cursor is an iterator, even if the original was an array.

Returns:
the new cursor

iterator

public Iterator<DBObject> iterator()
creates a copy of this cursor object that can be iterated. Note: - you can iterate the DBCursor itself without calling this method - no actual data is getting copied.

Specified by:
iterator in interface Iterable<DBObject>
Returns:

sort

public DBCursor sort(DBObject orderBy)
Sorts this cursor's elements. This method must be called before getting any object from the cursor.

Parameters:
orderBy - the fields by which to sort
Returns:
a cursor pointing to the first element of the sorted results

addSpecial

public DBCursor addSpecial(String name,
                           Object o)
adds a special operator like $maxScan or $returnKey e.g. addSpecial( "$returnKey" , 1 ) e.g. addSpecial( "$maxScan" , 100 )

Parameters:
name -
o -
Returns:

MongoDB Doc Links

hint

public DBCursor hint(DBObject indexKeys)
Informs the database of indexed fields of the collection in order to improve performance.

Parameters:
indexKeys - a DBObject with index names as keys
Returns:
same DBCursor for chaining operations

hint

public DBCursor hint(String indexName)
Informs the database of an indexed field of the collection in order to improve performance.

Parameters:
indexName - the name of an index
Returns:
same DBCursort for chaining operations

snapshot

public DBCursor snapshot()
Use snapshot mode for the query. Snapshot mode assures no duplicates are returned, or objects missed, which were present at both the start and end of the query's execution (if an object is new during the query, or deleted during the query, it may or may not be returned, even with snapshot mode). Note that short query responses (less than 1MB) are always effectively snapshotted. Currently, snapshot mode may not be used with sorting or explicit hints.

Returns:
same DBCursor for chaining operations

explain

public DBObject explain()
Returns an object containing basic information about the execution of the query that created this cursor This creates a DBObject with the key/value pairs: "cursor" : cursor type "nScanned" : number of records examined by the database for this query "n" : the number of records that the database returned "millis" : how long it took the database to execute the query

Returns:
a DBObject
MongoDB Doc Links

limit

public DBCursor limit(int n)
Limits the number of elements returned. Note: parameter n should be positive, although a negative value is supported for legacy reason. Passing a negative value will call batchSize(int) which is the preferred method.

Parameters:
n - the number of elements to return
Returns:
a cursor to iterate the results
MongoDB Doc Links

batchSize

public DBCursor batchSize(int n)
Limits the number of elements returned in one batch. A cursor typically fetches a batch of result objects and store them locally. If batchSize is positive, it represents the size of each batch of objects retrieved. It can be adjusted to optimize performance and limit data transfer. If batchSize is negative, it will limit of number objects returned, that fit within the max batch size limit (usually 4MB), and cursor will be closed. For example if batchSize is -10, then the server will return a maximum of 10 documents and as many as can fit in 4MB, then close the cursor. Note that this feature is different from limit() in that documents must fit within a maximum size, and it removes the need to send a request to close the cursor server-side. The batch size can be changed even after a cursor is iterated, in which case the setting will apply on the next batch retrieval.

Parameters:
n - the number of elements to return in a batch
Returns:

skip

public DBCursor skip(int n)
Discards a given number of elements at the beginning of the cursor.

Parameters:
n - the number of elements to skip
Returns:
a cursor pointing to the new first element of the results
Throws:
RuntimeException - if the cursor has started to be iterated through

getCursorId

public long getCursorId()
gets the cursor id.

Returns:
the cursor id, or 0 if there is no active cursor.

close

public void close()
kills the current cursor on the server.


slaveOk

public DBCursor slaveOk()
makes this query ok to run on a slave node

Returns:

addOption

public DBCursor addOption(int option)
adds a query option - see Bytes.QUERYOPTION_* for list

Parameters:
option -
Returns:

setOptions

public void setOptions(int options)
sets the query option - see Bytes.QUERYOPTION_* for list

Parameters:
options -

resetOptions

public void resetOptions()
resets the query options


getOptions

public int getOptions()
gets the query options

Returns:

numGetMores

public int numGetMores()
gets the number of times, so far, that the cursor retrieved a batch from the database

Returns:

getSizes

public List<Integer> getSizes()
gets a list containing the number of items received in each batch

Returns:

numSeen

public int numSeen()
Returns the number of objects through which the cursor has iterated.

Returns:
the number of objects seen

hasNext

public boolean hasNext()
                throws MongoException
Checks if there is another object available

Specified by:
hasNext in interface Iterator<DBObject>
Returns:
Throws:
MongoException

next

public DBObject next()
              throws MongoException
Returns the object the cursor is at and moves the cursor ahead by one.

Specified by:
next in interface Iterator<DBObject>
Returns:
the next element
Throws:
MongoException

curr

public DBObject curr()
Returns the element the cursor is at.

Returns:
the next element

remove

public void remove()
Not implemented.

Specified by:
remove in interface Iterator<DBObject>

length

public int length()
           throws MongoException
pulls back all items into an array and returns the number of objects. Note: this can be resource intensive

Returns:
the number of elements in the array
Throws:
MongoException
See Also:
count(), size()

toArray

public List<DBObject> toArray()
                       throws MongoException
Converts this cursor to an array.

Returns:
an array of elements
Throws:
MongoException

toArray

public List<DBObject> toArray(int max)
                       throws MongoException
Converts this cursor to an array.

Parameters:
max - the maximum number of objects to return
Returns:
an array of objects
Throws:
MongoException

itcount

public int itcount()
for testing only! Iterates cursor and counts objects

Returns:
num objects
See Also:
count()

count

public int count()
          throws MongoException
Counts the number of objects matching the query This does not take limit/skip into consideration

Returns:
the number of objects
Throws:
MongoException
See Also:
size()

size

public int size()
         throws MongoException
Counts the number of objects matching the query this does take limit/skip into consideration

Returns:
the number of objects
Throws:
MongoException
See Also:
count()

getKeysWanted

public DBObject getKeysWanted()
gets the fields to be returned

Returns:

getQuery

public DBObject getQuery()
gets the query

Returns:

getCollection

public DBCollection getCollection()
gets the collection

Returns:

getServerAddress

public ServerAddress getServerAddress()
Gets the Server Address of the server that data is pulled from. Note that this information is not available if no data has been retrieved yet. Availability is specific to underlying implementation and may vary.

Returns:

toString

public String toString()
Overrides:
toString in class Object