bson
– BSON (Binary JSON) Encoding and Decodingbinary
– Tools for representing binary data to be stored in MongoDBcode
– Tools for representing JavaScript codecodec_options
– Tools for specifying BSON codec optionsdatetime_ms
– Support for BSON UTC Datetimedbref
– Tools for manipulating DBRefs (references to documents stored in MongoDB)decimal128
– Support for BSON Decimal128errors
– Exceptions raised by thebson
packageint64
– Tools for representing BSON int64json_util
– Tools for using Python’sjson
module with BSON documentsmax_key
– Representation for the MongoDB internal MaxKey typemin_key
– Representation for the MongoDB internal MinKey typeobjectid
– Tools for working with MongoDB ObjectIdsraw_bson
– Tools for representing raw BSON documents.regex
– Tools for representing MongoDB regular expressionsson
– Tools for working with SON, an ordered mappingtimestamp
– Tools for representing MongoDB internal Timestampstz_util
– Utilities for dealing with timezones in Pythonpymongo
– Python driver for MongoDBpymongoasync
– Async Python driver for MongoDBchange_stream
– Watch changes on a collection, database, or clusterclient_session
– Logical sessions for sequential operationscollection
– Collection level operationscommand_cursor
– Tools for iterating over MongoDB command resultscursor
– Tools for iterating over MongoDB query resultsdatabase
– Database level operationsmongo_client
– Tools for connecting to MongoDBauth_oidc
– MONGODB-OIDC Authenticationchange_stream
– Watch changes on a collection, database, or clusterclient_options
– Read only configuration options for a MongoClient.client_session
– Logical sessions for sequential operationscollation
– Tools for working with collations.collection
– Collection level operationscommand_cursor
– Tools for iterating over MongoDB command resultscursor
– Tools for iterating over MongoDB query resultsdatabase
– Database level operationsdriver_info
encryption
– Client-Side Field Level Encryptionencryption_options
– Automatic Client-Side Field Level Encryptionerrors
– Exceptions raised by thepymongo
packagemongo_client
– Tools for connecting to MongoDBmonitoring
– Tools for monitoring driver events.operations
– Operation class definitionspool
– Pool module for use with a MongoDB client.read_concern
– Tools for working with read concern.read_preferences
– Utilities for choosing which member of a replica set to read from.results
– Result class definitionsserver_api
– Support for MongoDB Stable APIserver_description
– An object representation of a server the driver is connected to.topology_description
– An object representation of a deployment of MongoDB servers.uri_parser
– Tools to parse and validate a MongoDB URIwrite_concern
– Tools for specifying write concernevent_loggers
– Example loggersgridfs
– Tools for working with GridFScursor
– Tools for iterating over MongoDB query results¶Cursor class to iterate over Mongo query results.
The standard cursor type.
The tailable cursor type.
Tailable cursors are only for use with capped collections. They are notclosed when the last data is retrieved but are kept open and the cursorlocation marks the final document position. If more data is receivediteration of the cursor will continue from the last document received.
A tailable cursor with the await option set.
Creates a tailable cursor that will wait for a few seconds after returningthe full result set so that it can capture and return additional data addedduring the query.
An exhaust cursor.
MongoDB will stream batched results to the client without waiting for theclient to request each batch, reducing latency.
Create a new cursor.
Should not be called directly by application developers - seefind()
instead.
See also
The MongoDB documentation oncursors.
collection (Collection[_DocumentType])
filter (Optional[Mapping[str,Any]])
projection (Optional[Union[Mapping[str,Any],Iterable[str]]])
skip (int)
limit (int)
no_cursor_timeout (bool)
cursor_type (int)
sort (Optional[_Sort])
allow_partial_results (bool)
oplog_replay (bool)
batch_size (int)
collation (Optional[_CollationIn])
hint (Optional[_Hint])
max_scan (Optional[int])
max_time_ms (Optional[int])
max (Optional[_Sort])
min (Optional[_Sort])
return_key (Optional[bool])
show_record_id (Optional[bool])
snapshot (Optional[bool])
comment (Optional[Any])
session (Optional[ClientSession])
allow_disk_use (Optional[bool])
let (Optional[bool])
See__getitem__()
and read the warning.
Get a single document or a slice of documents from this cursor.
Warning
ACursor
is not a Pythonlist
. Eachindex access or slice requires that a new query be run using skipand limit. Do not iterate the cursor using index accesses.The following example isextremely inefficient and may returnsurprising results:
cursor=db.collection.find()# Warning: This runs a new query for each document.# Don't do this!foridxinrange(10):print(cursor[idx])
RaisesInvalidOperation
if thiscursor has already been used.
To get a single document use an integral index, e.g.:
>>>db.test.find()[50]
AnIndexError
will be raised if the index is negativeor greater than the amount of documents in this cursor. Anylimit previously applied to this cursor will be ignored.
To get a slice of documents use a slice index, e.g.:
>>>db.test.find()[20:25]
This will return this cursor with a limit of5
and skip of20
applied. Using a slice index will override any priorlimits or skips applied to this cursor (including thoseapplied through previous calls to this method). RaisesIndexError
when the slice has a step, a negativestart value, or a stop value less than or equal to the startvalue.
index – An integer or slice index to be applied to this cursor
Set arbitrary query flags using a bitmask.
To set the tailable flag:cursor.add_option(2)
The (host, port) of the server used, or None.
Changed in version 3.0:Renamed from “conn_id”.
Does this cursor have the potential to return more data?
This is mostly useful withtailable cursorssince they will stop iterating even though theymay return moreresults in the future.
With regular cursors, simply use a for loop instead ofalive
:
fordocincollection.find():print(doc)
Specifies whether MongoDB can use temporary disk files whileprocessing a blocking sort operation.
RaisesTypeError
ifallow_disk_use is not a boolean.
Note
allow_disk_use requires server version>= 4.4
allow_disk_use (bool) – if True, MongoDB may use temporarydisk files to store data exceeding the system memory limit whileprocessing a blocking sort operation.
Cursor[_DocumentType]
Added in version 3.11.
Limits the number of documents returned in one batch. Each batchrequires a round trip to the server. It can be adjusted to optimizeperformance and limit data transfer.
Note
batch_size can not override MongoDB’s internal limits on theamount of data it will return to the client in a single batch (i.eif you set batch size to 1,000,000,000, MongoDB will currently onlyreturn 4-16MB of results per batch).
RaisesTypeError
ifbatch_size is not an integer.RaisesValueError
ifbatch_size is less than0
.RaisesInvalidOperation
if thisCursor
has already been used. The lastbatch_sizeapplied to this cursor takes precedence.
Get a clone of this cursor.
Returns a new Cursor instance with options matching those that havebeen set on the current instance. The clone will be completelyunevaluated, even if the current instance has been partially orcompletely evaluated.
Cursor[_DocumentType]
Explicitly close / kill this cursor.
None
Adds aCollation
to this query.
RaisesTypeError
ifcollation is not an instance ofCollation
or adict
. RaisesInvalidOperation
if thisCursor
hasalready been used. Only the last collation applied to this cursor hasany effect.
TheCollection
that thisCursor
is iterating.
Adds a ‘comment’ to the cursor.
http://mongodb.com/docs/manual/reference/operator/comment/
comment (Any) – A string to attach to the query to help interpret andtrace the operation in the server logs and in profile data.
Cursor[_DocumentType]
Added in version 2.7.
Get a list of distinct values forkey among all documentsin the result set of this query.
RaisesTypeError
ifkey is not an instance ofstr
.
Thedistinct()
method obeys theread_preference
of theCollection
instance on whichfind()
was called.
Returns an explain plan record for this cursor.
Note
This method uses the default verbosity mode of theexplain command,allPlansExecution
. To use a different verbosity usecommand()
to run the explaincommand directly.
See also
The MongoDB documentation onexplain.
_DocumentType
Adds a ‘hint’, telling Mongo the proper index to use for the query.
Judicious use of hints can greatly improve queryperformance. When doing a query on multiple fields (at leastone of which is indexed) pass the indexed field as a hint tothe query. RaisesOperationFailure
if theprovided hint requires an index that does not exist on this collection,and raisesInvalidOperation
if this cursor hasalready been used.
index should be an index as passed tocreate_index()
(e.g.[('field',ASCENDING)]
) or the name of the index.Ifindex isNone
any existing hint for this query iscleared. The last hint applied to this cursor takes precedenceover all others.
Limits the number of results to be returned by this cursor.
RaisesTypeError
iflimit is not an integer. RaisesInvalidOperation
if thisCursor
has already been used. The lastlimit applied to this cursortakes precedence. A limit of0
is equivalent to no limit.
See also
The MongoDB documentation onlimit.
Addsmax
operator that specifies upper bound for specific index.
When usingmax
,hint()
should also be configured to ensurethe query uses the expected index and starting in MongoDB 4.2hint()
will be required.
spec (Sequence[str |Tuple[str,int |str |Mapping[str,Any]]]|Mapping[str,Any]) – a list of field, limit pairs specifying the exclusiveupper bound for all keys of a specific index in order.
Cursor[_DocumentType]
Changed in version 3.8:Deprecated cursors that usemax
without ahint()
.
Added in version 2.7.
Specifies a time limit for a getMore operation on aTAILABLE_AWAIT
cursor. For all othertypes of cursor max_await_time_ms is ignored.
RaisesTypeError
ifmax_await_time_ms is not an integer orNone
. RaisesInvalidOperation
if thisCursor
has already been used.
Note
max_await_time_ms requires server version>= 3.2
max_await_time_ms (int |None) – the time limit after which the operation isaborted
Cursor[_DocumentType]
Added in version 3.2.
DEPRECATED - Limit the number of documents to scan whenperforming the query.
RaisesInvalidOperation
if thiscursor has already been used. Only the lastmax_scan()
applied to this cursor has any effect.
max_scan (int |None) – the maximum number of documents to scan
Cursor[_DocumentType]
Changed in version 3.7:Deprecatedmax_scan()
. Support for this option is deprecated inMongoDB 4.0. Usemax_time_ms()
instead to limit server sideexecution time.
Specifies a time limit for a query operation. If the specifiedtime is exceeded, the operation will be aborted andExecutionTimeout
is raised. Ifmax_time_msisNone
no limit is applied.
RaisesTypeError
ifmax_time_ms is not an integer orNone
.RaisesInvalidOperation
if thisCursor
has already been used.
Addsmin
operator that specifies lower bound for specific index.
When usingmin
,hint()
should also be configured to ensurethe query uses the expected index and starting in MongoDB 4.2hint()
will be required.
spec (Sequence[str |Tuple[str,int |str |Mapping[str,Any]]]|Mapping[str,Any]) – a list of field, limit pairs specifying the inclusivelower bound for all keys of a specific index in order.
Cursor[_DocumentType]
Changed in version 3.8:Deprecated cursors that usemin
without ahint()
.
Added in version 2.7.
Advance the cursor.
_DocumentType
Unset arbitrary query flags using a bitmask.
To unset the tailable flag:cursor.remove_option(2)
Rewind this cursor to its unevaluated state.
Reset this cursor if it has been partially or completely evaluated.Any options that are present on the cursor will remain in effect.Future iterating performed on this cursor will cause new queries tobe sent to the server, even if the resultant data has already beenretrieved by this cursor.
Cursor[_DocumentType]
The cursor’sClientSession
, or None.
Added in version 3.6.
Skips the firstskip results of this cursor.
RaisesTypeError
ifskip is not an integer. RaisesValueError
ifskip is less than0
. RaisesInvalidOperation
if thisCursor
hasalready been used. The lastskip applied to this cursor takesprecedence.
Sorts this cursor’s results.
Pass a field name and a direction, eitherASCENDING
orDESCENDING
.:
fordocincollection.find().sort('field',pymongo.ASCENDING):print(doc)
To sort by multiple fields, pass a list of (key, direction) pairs.If just a name is given,ASCENDING
will be inferred:
fordocincollection.find().sort(['field1',('field2',pymongo.DESCENDING)]):print(doc)
Text search results can be sorted by relevance:
cursor=db.test.find({'$text':{'$search':'some words'}},{'score':{'$meta':'textScore'}})# Sort by 'score' field.cursor.sort([('score',{'$meta':'textScore'})])fordocincursor:print(doc)
For more advanced text search functionality, see MongoDB’sAtlas Search.
RaisesInvalidOperation
if this cursor hasalready been used. Only the lastsort()
applied to thiscursor has any effect.
Cursor[_DocumentType]
Converts the contents of this cursor to a list more efficiently than[docfordocincursor]
.
To use:
>>>cursor.to_list()
Or, to read at most n items from the cursor:
>>>cursor.to_list(n)
If the cursor is empty or has no more results, an empty list will be returned.
Added in version 4.9.
Adds a$where clause to this query.
Thecode argument must be an instance ofstr
orCode
containing a JavaScript expression.This expression will be evaluated for each document scanned.Only those documents for which the expression evaluates totrue will be returned as results. The keywordthis refersto the object currently being scanned. For example:
# Find all documents where field "a" is less than "b" plus "c".fordocindb.test.find().where('this.a < (this.b + this.c)'):print(doc)
RaisesTypeError
ifcode is not an instance ofstr
. RaisesInvalidOperation
if thisCursor
has already been used. Only the last call towhere()
applied to aCursor
has any effect.
Create a new cursor / iterator over raw batches of BSON data.
Should not be called directly by application developers -seefind_raw_batches()
instead.
See also
The MongoDB documentation oncursors.
collection (Collection[_DocumentType])
args (Any)
kwargs (Any)
cursor
– Tools for iterating over MongoDB query resultsCursorType
Cursor
Cursor.__getitem__()
Cursor.add_option()
Cursor.address
Cursor.alive
Cursor.allow_disk_use()
Cursor.batch_size()
Cursor.clone()
Cursor.close()
Cursor.collation()
Cursor.collection
Cursor.comment()
Cursor.cursor_id
Cursor.distinct()
Cursor.explain()
Cursor.hint()
Cursor.limit()
Cursor.max()
Cursor.max_await_time_ms()
Cursor.max_scan()
Cursor.max_time_ms()
Cursor.min()
Cursor.next()
Cursor.remove_option()
Cursor.retrieved
Cursor.rewind()
Cursor.session
Cursor.skip()
Cursor.sort()
Cursor.to_list()
Cursor.where()
RawBatchCursor