MotorCursor

class motor.MotorCursor(cursor, collection)

You don’t construct a MotorCursor yourself, but acquire one from MotorCollection.find().

Note

There is no need to manually close cursors; they are closed by the server after being fully iterated with to_list(), each(), or fetch_next(), or automatically closed by the client when the MotorCursor is cleaned up by the garbage collector.

c[index]

See __getitem__().

__getitem__(index)

Get a slice of documents from this cursor.

Raises InvalidOperation if this cursor has already been used.

To get a single document use an integral index, e.g.:

>>> @gen.coroutine
... def fifth_item():
...     yield collection.insert([{'i': i} for i in range(10)])
...     cursor = collection.find().sort([('i', 1)])[5]
...     yield cursor.fetch_next
...     doc = cursor.next_object()
...     print doc['i']
...
>>> IOLoop.current().run_sync(fifth_item)
5

Any limit previously applied to this cursor will be ignored.

The cursor returns None if the index is greater than or equal to the length of the result set.

>>> @gen.coroutine
... def one_thousandth_item():
...     cursor = collection.find().sort([('i', 1)])[1000]
...     yield cursor.fetch_next
...     print cursor.next_object()
...
>>> IOLoop.current().run_sync(one_thousandth_item)
None

To get a slice of documents use a slice index like cursor[start:end].

>>> @gen.coroutine
... def second_through_fifth_item():
...     cursor = collection.find().sort([('i', 1)])[2:6]
...     while (yield cursor.fetch_next):
...         doc = cursor.next_object()
...         sys.stdout.write(str(doc['i']) + ', ')
...     print 'done'
...
>>> IOLoop.current().run_sync(second_through_fifth_item)
2, 3, 4, 5, done

This will apply a skip of 2 and a limit of 4 to the cursor. Using a slice index overrides prior limits or skips applied to this cursor (including those applied through previous calls to this method).

Raises IndexError when the slice has a step, a negative start value, or a stop value less than or equal to the start value.

Parameters :
  • index: An integer or slice index to be applied to this cursor
add_option(mask)

Set arbitary query flags using a bitmask.

To set the tailable flag: cursor.add_option(2)

batch_size(batch_size)

Limits the number of documents returned in one batch. Each batch requires a round trip to the server. It can be adjusted to optimize performance and limit data transfer.

Note

batch_size can not override MongoDB’s internal limits on the amount of data it will return to the client in a single batch (i.e if you set batch size to 1,000,000,000, MongoDB will currently only return 4-16MB of results per batch).

Raises TypeError if batch_size is not an instance of int. Raises ValueError if batch_size is less than 0. Raises InvalidOperation if this Cursor has already been used. The last batch_size applied to this cursor takes precedence.

Parameters :
  • batch_size: The size of each batch of results requested.
clone()

Get a clone of this cursor.

close(callback=None)

Explicitly kill this cursor on the server. If iterating with each(), cease.

Parameters :
  • callback (optional): function taking (result, error).

If a callback is passed, returns None, else returns a Future.

count(with_limit_and_skip=False, callback=None)

Get the size of the results set for this query.

Returns the number of documents in the results set for this query. Does not take limit() and skip() into account by default - set with_limit_and_skip to True if that is the desired behavior. Raises OperationFailure on a database error.

With MongoReplicaSetClient or MasterSlaveConnection, if read_preference is not pymongo.read_preferences.ReadPreference.PRIMARY or pymongo.read_preferences.ReadPreference.PRIMARY_PREFERRED, or (deprecated) slave_okay is True, the count command will be sent to a secondary or slave.

Parameters :
  • with_limit_and_skip (optional): take any limit() or skip() that has been applied to this cursor into account when getting the count
  • callback (optional): function taking (result, error), executed when operation completes

Note

The with_limit_and_skip parameter requires server version >= 1.1.4-

If a callback is passed, returns None, else returns a Future.

distinct(key, callback=None)

Get a list of distinct values for key among all documents in the result set of this query.

Raises TypeError if key is not an instance of basestring (str in python 3).

With MongoReplicaSetClient or MasterSlaveConnection, if read_preference is not pymongo.read_preferences.ReadPreference.PRIMARY or (deprecated) slave_okay is True the distinct command will be sent to a secondary or slave.

Parameters :
  • key: name of key for which we want to get the distinct values
  • callback (optional): function taking (result, error), executed when operation completes

Note

Requires server version >= 1.1.3+

If a callback is passed, returns None, else returns a Future.

each(callback)

Iterates over all the documents for this cursor.

each returns immediately, and callback is executed asynchronously for each document. callback is passed (None, None) when iteration is complete.

Cancel iteration early by returning False from the callback. (Only False cancels iteration: returning None or 0 does not.)

>>> from tornado.ioloop import IOLoop
>>> collection = MotorClient().open_sync().test.collection
>>> def inserted(result, error):
...     global cursor
...     if error:
...         raise error
...     cursor = collection.find().sort([('_id', 1)])
...     cursor.each(callback=each)
...
>>> def each(result, error):
...     if error:
...         raise error
...     elif result:
...         sys.stdout.write(str(result['_id']) + ', ')
...     else:
...         # Iteration complete
...         IOLoop.current().stop()
...         print 'done'
...
>>> collection.insert(
...     [{'_id': i} for i in range(5)], callback=inserted)
>>> IOLoop.current().start()
0, 1, 2, 3, 4, done

Note

Unlike other Motor methods, each requires a callback and does not return a Future, so it cannot be used with gen.coroutine. to_list() or fetch_next are much easier to use.

Parameters :
  • callback: function taking (document, error)
explain(callback=None)

Returns an explain plan record for this cursor.

See general MongoDB documentation

explain

Parameters :
  • callback (optional): function taking (result, error), executed when operation completes

If a callback is passed, returns None, else returns a Future.

hint(index)

Adds a ‘hint’, telling Mongo the proper index to use for the query.

Judicious use of hints can greatly improve query performance. When doing a query on multiple fields (at least one of which is indexed) pass the indexed field as a hint to the query. Hinting will not do anything if the corresponding index does not exist. Raises InvalidOperation if this cursor has already been used.

index should be an index as passed to create_index() (e.g. [('field', ASCENDING)]). If index is None any existing hints for this query are cleared. The last hint applied to this cursor takes precedence over all others.

Parameters :
  • index: index to hint on (as an index specifier)
limit(limit)

Limits the number of results to be returned by this cursor.

Raises TypeError if limit is not an instance of int. Raises InvalidOperation if this cursor has already been used. The last limit applied to this cursor takes precedence. A limit of 0 is equivalent to no limit.

Parameters :
  • limit: the number of results to return

See general MongoDB documentation

limit

max_scan(max_scan)

Limit the number of documents to scan when performing the query.

Raises InvalidOperation if this cursor has already been used. Only the last max_scan() applied to this cursor has any effect.

Parameters :
  • max_scan: the maximum number of documents to scan

Note

Requires server version >= 1.5.1

next_object()

Get a document from the most recently fetched batch, or None. See fetch_next.

remove_option(mask)

Unset arbitrary query flags using a bitmask.

To unset the tailable flag: cursor.remove_option(2)

rewind()

Rewind this cursor to its unevaluated state.

skip(skip)

Skips the first skip results of this cursor.

Raises TypeError if skip is not an instance of int. Raises InvalidOperation if this cursor has already been used. The last skip applied to this cursor takes precedence.

Parameters :
  • skip: the number of results to skip
sort(key_or_list, direction=None)

Sorts this cursor’s results.

Takes either a single key and a direction, or a list of (key, direction) pairs. The key(s) must be an instance of (str, unicode), and the direction(s) must be one of (ASCENDING, DESCENDING). Raises InvalidOperation if this cursor has already been used. Only the last sort() applied to this cursor has any effect.

Parameters :
  • key_or_list: a single key or a list of (key, direction) pairs specifying the keys to sort on
  • direction (optional): only used if key_or_list is a single key, if not given ASCENDING is assumed
to_list(length, callback=None)

Get a list of documents.

>>> @gen.coroutine
... def f():
...     yield collection.insert([{'_id': i} for i in range(4)])
...     cursor = collection.find().sort([('_id', 1)])
...     docs = yield cursor.to_list(length=2)
...     while docs:
...         print docs
...         docs = yield cursor.to_list(length=2)
...
...     print 'done'
...
>>> IOLoop.current().run_sync(f)
[{u'_id': 0}, {u'_id': 1}]
[{u'_id': 2}, {u'_id': 3}]
done
Parameters :
  • length: maximum number of documents to return for this call
  • callback (optional): function taking (document, error)

If a callback is passed, returns None, else returns a Future.

Changed in version 0.2: length parameter is no longer optional.

where(code)

Adds a $where clause to this query.

The code argument must be an instance of basestring (str in python 3) or Code containing a JavaScript expression. This expression will be evaluated for each document scanned. Only those documents for which the expression evaluates to true will be returned as results. The keyword this refers to the object currently being scanned.

Raises TypeError if code is not an instance of basestring (str in python 3). Raises InvalidOperation if this Cursor has already been used. Only the last call to where() applied to a Cursor has any effect.

Parameters :
  • code: JavaScript expression to use as a filter
alive

Does this cursor have the potential to return more data?

This is mostly useful with tailable cursors since they will stop iterating even though they may return more results in the future.

cursor_id

Returns the id of the cursor

Useful if you need to manage cursor ids and want to handle killing cursors manually using kill_cursors()

fetch_next

A Future used with gen.coroutine to asynchronously retrieve the next document in the result set, fetching a batch of documents from the server if necessary. Resolves to False if there are no more documents, otherwise next_object() is guaranteed to return a document.

>>> @gen.coroutine
... def f():
...     yield collection.insert([{'_id': i} for i in range(5)])
...     cursor = collection.find().sort([('_id', 1)])
...     while (yield cursor.fetch_next):
...         doc = cursor.next_object()
...         sys.stdout.write(str(doc['_id']) + ', ')
...     print 'done'
...
>>> IOLoop.current().run_sync(f)
0, 1, 2, 3, 4, done

Note

While it appears that fetch_next retrieves each document from the server individually, the cursor actually fetches documents efficiently in large batches.

Previous topic

MotorCollection

Next topic

Motor GridFS Classes

This Page