collection
– Collection level operations¶
Collection level utilities for Mongo.
- pymongo.ASCENDING = 1¶
Ascending sort order.
- pymongo.DESCENDING = -1¶
Descending sort order.
- pymongo.GEO2D = '2d'¶
Index specifier for a 2-dimensional geospatial index.
- pymongo.GEOSPHERE = '2dsphere'¶
Index specifier for a spherical geospatial index.
New in version 2.5.
- pymongo.HASHED = 'hashed'¶
Index specifier for a hashed index.
New in version 2.5.
- pymongo.TEXT = 'text'¶
Index specifier for a text index.
See also
MongoDB’s Atlas Search which offers more advanced text search functionality.
New in version 2.7.1.
- class pymongo.collection.ReturnDocument¶
An enum used with
find_one_and_replace()
andfind_one_and_update()
.- BEFORE¶
Return the original document before it was updated/replaced, or
None
if no document matches the query.
- AFTER¶
Return the updated/replaced or inserted document.
- class pymongo.collection.Collection(database, name, create=False, **kwargs)¶
Get / create a Mongo collection.
Raises
TypeError
if name is not an instance ofbasestring
(str
in python 3). RaisesInvalidName
if name is not a valid collection name. Any additional keyword arguments will be used as options passed to the create command. Seecreate_collection()
for valid options.If create is
True
, collation is specified, or any additional keyword arguments are present, acreate
command will be sent, usingsession
if specified. Otherwise, acreate
command will not be sent and the collection will be created implicitly on first use. The optionalsession
argument is only used for thecreate
command, it is not associated with the collection afterward.- Parameters
database: the database to get a collection from
name: the name of the collection to get
create (optional): if
True
, force collection creation even without options being setcodec_options (optional): An instance of
CodecOptions
. IfNone
(the default) database.codec_options is used.read_preference (optional): The read preference to use. If
None
(the default) database.read_preference is used.write_concern (optional): An instance of
WriteConcern
. IfNone
(the default) database.write_concern is used.read_concern (optional): An instance of
ReadConcern
. IfNone
(the default) database.read_concern is used.collation (optional): An instance of
Collation
. If a collation is provided, it will be passed to the create collection command.session (optional): a
ClientSession
that is used with the create collection command**kwargs (optional): additional keyword arguments will be passed as options for the create collection command
Changed in version 4.2: Added the
clusteredIndex
andencryptedFields
parameters.Changed in version 4.0: Removed the reindex, map_reduce, inline_map_reduce, parallel_scan, initialize_unordered_bulk_op, initialize_ordered_bulk_op, group, count, insert, save, update, remove, find_and_modify, and ensure_index methods. See the PyMongo 4 Migration Guide.
Changed in version 3.6: Added
session
parameter.Changed in version 3.4: Support the collation option.
Changed in version 3.2: Added the read_concern option.
Changed in version 3.0: Added the codec_options, read_preference, and write_concern options. Removed the uuid_subtype attribute.
Collection
no longer returns an instance ofCollection
for attribute names with leading underscores. You must use dict-style lookups instead::collection[‘__my_collection__’]
Not:
collection.__my_collection__
See also
The MongoDB documentation on collections.
- c[name] || c.name
Get the name sub-collection of
Collection
c.Raises
InvalidName
if an invalid collection name is used.
- full_name¶
The full name of this
Collection
.The full name is of the form database_name.collection_name.
- name¶
The name of this
Collection
.
- database¶
The
Database
that thisCollection
is a part of.
- codec_options¶
Read only access to the
CodecOptions
of this instance.
- read_preference¶
Read only access to the read preference of this instance.
Changed in version 3.0: The
read_preference
attribute is now read only.
- write_concern¶
Read only access to the
WriteConcern
of this instance.Changed in version 3.0: The
write_concern
attribute is now read only.
- read_concern¶
Read only access to the
ReadConcern
of this instance.New in version 3.2.
- with_options(codec_options: Optional[bson.codec_options.CodecOptions] = None, read_preference: Optional[pymongo.read_preferences._ServerMode] = None, write_concern: Optional[pymongo.write_concern.WriteConcern] = None, read_concern: Optional[ReadConcern] = None) Collection[_DocumentType] ¶
Get a clone of this collection changing the specified settings.
>>> coll1.read_preference Primary() >>> from pymongo import ReadPreference >>> coll2 = coll1.with_options(read_preference=ReadPreference.SECONDARY) >>> coll1.read_preference Primary() >>> coll2.read_preference Secondary(tag_sets=None)
- Parameters
codec_options (optional): An instance of
CodecOptions
. IfNone
(the default) thecodec_options
of thisCollection
is used.read_preference (optional): The read preference to use. If
None
(the default) theread_preference
of thisCollection
is used. Seeread_preferences
for options.write_concern (optional): An instance of
WriteConcern
. IfNone
(the default) thewrite_concern
of thisCollection
is used.read_concern (optional): An instance of
ReadConcern
. IfNone
(the default) theread_concern
of thisCollection
is used.
- bulk_write(requests: Sequence[Union[pymongo.operations.InsertOne, pymongo.operations.DeleteOne, pymongo.operations.DeleteMany, pymongo.operations.ReplaceOne, pymongo.operations.UpdateOne, pymongo.operations.UpdateMany]], ordered: bool = True, bypass_document_validation: bool = False, session: Optional[ClientSession] = None, comment: Optional[Any] = None, let: Optional[Mapping] = None) pymongo.results.BulkWriteResult ¶
Send a batch of write operations to the server.
Requests are passed as a list of write operation instances (
InsertOne
,UpdateOne
,UpdateMany
,ReplaceOne
,DeleteOne
, orDeleteMany
).>>> for doc in db.test.find({}): ... print(doc) ... {'x': 1, '_id': ObjectId('54f62e60fba5226811f634ef')} {'x': 1, '_id': ObjectId('54f62e60fba5226811f634f0')} >>> # DeleteMany, UpdateOne, and UpdateMany are also available. ... >>> from pymongo import InsertOne, DeleteOne, ReplaceOne >>> requests = [InsertOne({'y': 1}), DeleteOne({'x': 1}), ... ReplaceOne({'w': 1}, {'z': 1}, upsert=True)] >>> result = db.test.bulk_write(requests) >>> result.inserted_count 1 >>> result.deleted_count 1 >>> result.modified_count 0 >>> result.upserted_ids {2: ObjectId('54f62ee28891e756a6e1abd5')} >>> for doc in db.test.find({}): ... print(doc) ... {'x': 1, '_id': ObjectId('54f62e60fba5226811f634f0')} {'y': 1, '_id': ObjectId('54f62ee2fba5226811f634f1')} {'z': 1, '_id': ObjectId('54f62ee28891e756a6e1abd5')}
- Parameters
requests: A list of write operations (see examples above).
ordered (optional): If
True
(the default) requests will be performed on the server serially, in the order provided. If an error occurs all remaining operations are aborted. IfFalse
requests will be performed on the server in arbitrary order, possibly in parallel, and all operations will be attempted.bypass_document_validation: (optional) If
True
, allows the write to opt-out of document level validation. Default isFalse
.session (optional): a
ClientSession
.comment (optional): A user-provided comment to attach to this command.
let (optional): Map of parameter names and values. Values must be constant or closed expressions that do not reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. “$$var”).
- Returns
An instance of
BulkWriteResult
.
Note
bypass_document_validation requires server version >= 3.2
Changed in version 4.1: Added
comment
parameter. Addedlet
parameter.Changed in version 3.6: Added
session
parameter.Changed in version 3.2: Added bypass_document_validation support
New in version 3.0.
- insert_one(document: Union[MutableMapping[str, Any], RawBSONDocument], bypass_document_validation: bool = False, session: Optional[ClientSession] = None, comment: Optional[Any] = None) pymongo.results.InsertOneResult ¶
Insert a single document.
>>> db.test.count_documents({'x': 1}) 0 >>> result = db.test.insert_one({'x': 1}) >>> result.inserted_id ObjectId('54f112defba522406c9cc208') >>> db.test.find_one({'x': 1}) {'x': 1, '_id': ObjectId('54f112defba522406c9cc208')}
- Parameters
document: The document to insert. Must be a mutable mapping type. If the document does not have an _id field one will be added automatically.
bypass_document_validation: (optional) If
True
, allows the write to opt-out of document level validation. Default isFalse
.session (optional): a
ClientSession
.comment (optional): A user-provided comment to attach to this command.
- Returns
An instance of
InsertOneResult
.
Note
bypass_document_validation requires server version >= 3.2
Changed in version 4.1: Added
comment
parameter.Changed in version 3.6: Added
session
parameter.Changed in version 3.2: Added bypass_document_validation support
New in version 3.0.
- insert_many(documents: Iterable[Union[MutableMapping[str, Any], RawBSONDocument]], ordered: bool = True, bypass_document_validation: bool = False, session: Optional[ClientSession] = None, comment: Optional[Any] = None) pymongo.results.InsertManyResult ¶
Insert an iterable of documents.
>>> db.test.count_documents({}) 0 >>> result = db.test.insert_many([{'x': i} for i in range(2)]) >>> result.inserted_ids [ObjectId('54f113fffba522406c9cc20e'), ObjectId('54f113fffba522406c9cc20f')] >>> db.test.count_documents({}) 2
- Parameters
documents: A iterable of documents to insert.
ordered (optional): If
True
(the default) documents will be inserted on the server serially, in the order provided. If an error occurs all remaining inserts are aborted. IfFalse
, documents will be inserted on the server in arbitrary order, possibly in parallel, and all document inserts will be attempted.bypass_document_validation: (optional) If
True
, allows the write to opt-out of document level validation. Default isFalse
.session (optional): a
ClientSession
.comment (optional): A user-provided comment to attach to this command.
- Returns
An instance of
InsertManyResult
.
Note
bypass_document_validation requires server version >= 3.2
Changed in version 4.1: Added
comment
parameter.Changed in version 3.6: Added
session
parameter.Changed in version 3.2: Added bypass_document_validation support
New in version 3.0.
- replace_one(filter: Mapping[str, Any], replacement: Mapping[str, Any], upsert: bool = False, bypass_document_validation: bool = False, collation: Optional[Union[Mapping[str, Any], Collation]] = None, hint: Optional[Union[str, Sequence[Tuple[str, Union[int, str, Mapping[str, Any]]]]]] = None, session: Optional[ClientSession] = None, let: Optional[Mapping[str, Any]] = None, comment: Optional[Any] = None) pymongo.results.UpdateResult ¶
Replace a single document matching the filter.
>>> for doc in db.test.find({}): ... print(doc) ... {'x': 1, '_id': ObjectId('54f4c5befba5220aa4d6dee7')} >>> result = db.test.replace_one({'x': 1}, {'y': 1}) >>> result.matched_count 1 >>> result.modified_count 1 >>> for doc in db.test.find({}): ... print(doc) ... {'y': 1, '_id': ObjectId('54f4c5befba5220aa4d6dee7')}
The upsert option can be used to insert a new document if a matching document does not exist.
>>> result = db.test.replace_one({'x': 1}, {'x': 1}, True) >>> result.matched_count 0 >>> result.modified_count 0 >>> result.upserted_id ObjectId('54f11e5c8891e756a6e1abd4') >>> db.test.find_one({'x': 1}) {'x': 1, '_id': ObjectId('54f11e5c8891e756a6e1abd4')}
- Parameters
filter: A query that matches the document to replace.
replacement: The new document.
upsert (optional): If
True
, perform an insert if no documents match the filter.bypass_document_validation: (optional) If
True
, allows the write to opt-out of document level validation. Default isFalse
.collation (optional): An instance of
Collation
.hint (optional): An index to use to support the query predicate specified either by its string name, or in the same format as passed to
create_index()
(e.g.[('field', ASCENDING)]
). This option is only supported on MongoDB 4.2 and above.session (optional): a
ClientSession
.let (optional): Map of parameter names and values. Values must be constant or closed expressions that do not reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. “$$var”).
comment (optional): A user-provided comment to attach to this command.
- Returns
An instance of
UpdateResult
.
Changed in version 4.1: Added
let
parameter. Addedcomment
parameter.Changed in version 3.11: Added
hint
parameter.Changed in version 3.6: Added
session
parameter.Changed in version 3.4: Added the collation option.
Changed in version 3.2: Added bypass_document_validation support.
New in version 3.0.
- update_one(filter: Mapping[str, Any], update: Union[Mapping[str, Any], Sequence[Mapping[str, Any]]], upsert: bool = False, bypass_document_validation: bool = False, collation: Optional[Union[Mapping[str, Any], Collation]] = None, array_filters: Optional[Sequence[Mapping[str, Any]]] = None, hint: Optional[Union[str, Sequence[Tuple[str, Union[int, str, Mapping[str, Any]]]]]] = None, session: Optional[ClientSession] = None, let: Optional[Mapping[str, Any]] = None, comment: Optional[Any] = None) pymongo.results.UpdateResult ¶
Update a single document matching the filter.
>>> for doc in db.test.find(): ... print(doc) ... {'x': 1, '_id': 0} {'x': 1, '_id': 1} {'x': 1, '_id': 2} >>> result = db.test.update_one({'x': 1}, {'$inc': {'x': 3}}) >>> result.matched_count 1 >>> result.modified_count 1 >>> for doc in db.test.find(): ... print(doc) ... {'x': 4, '_id': 0} {'x': 1, '_id': 1} {'x': 1, '_id': 2}
If
upsert=True
and no documents match the filter, create a new document based on the filter criteria and update modifications.>>> result = db.test.update_one({'x': -10}, {'$inc': {'x': 3}}, upsert=True) >>> result.matched_count 0 >>> result.modified_count 0 >>> result.upserted_id ObjectId('626a678eeaa80587d4bb3fb7') >>> db.test.find_one(result.upserted_id) {'_id': ObjectId('626a678eeaa80587d4bb3fb7'), 'x': -7}
- Parameters
filter: A query that matches the document to update.
update: The modifications to apply.
upsert (optional): If
True
, perform an insert if no documents match the filter.bypass_document_validation: (optional) If
True
, allows the write to opt-out of document level validation. Default isFalse
.collation (optional): An instance of
Collation
.array_filters (optional): A list of filters specifying which array elements an update should apply.
hint (optional): An index to use to support the query predicate specified either by its string name, or in the same format as passed to
create_index()
(e.g.[('field', ASCENDING)]
). This option is only supported on MongoDB 4.2 and above.session (optional): a
ClientSession
.let (optional): Map of parameter names and values. Values must be constant or closed expressions that do not reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. “$$var”).
comment (optional): A user-provided comment to attach to this command.
- Returns
An instance of
UpdateResult
.
Changed in version 4.1: Added
let
parameter. Addedcomment
parameter.Changed in version 3.11: Added
hint
parameter.Changed in version 3.9: Added the ability to accept a pipeline as the
update
.Changed in version 3.6: Added the
array_filters
andsession
parameters.Changed in version 3.4: Added the
collation
option.Changed in version 3.2: Added
bypass_document_validation
support.New in version 3.0.
- update_many(filter: Mapping[str, Any], update: Union[Mapping[str, Any], Sequence[Mapping[str, Any]]], upsert: bool = False, array_filters: Optional[Sequence[Mapping[str, Any]]] = None, bypass_document_validation: Optional[bool] = None, collation: Optional[Union[Mapping[str, Any], Collation]] = None, hint: Optional[Union[str, Sequence[Tuple[str, Union[int, str, Mapping[str, Any]]]]]] = None, session: Optional[ClientSession] = None, let: Optional[Mapping[str, Any]] = None, comment: Optional[Any] = None) pymongo.results.UpdateResult ¶
Update one or more documents that match the filter.
>>> for doc in db.test.find(): ... print(doc) ... {'x': 1, '_id': 0} {'x': 1, '_id': 1} {'x': 1, '_id': 2} >>> result = db.test.update_many({'x': 1}, {'$inc': {'x': 3}}) >>> result.matched_count 3 >>> result.modified_count 3 >>> for doc in db.test.find(): ... print(doc) ... {'x': 4, '_id': 0} {'x': 4, '_id': 1} {'x': 4, '_id': 2}
- Parameters
filter: A query that matches the documents to update.
update: The modifications to apply.
upsert (optional): If
True
, perform an insert if no documents match the filter.bypass_document_validation (optional): If
True
, allows the write to opt-out of document level validation. Default isFalse
.collation (optional): An instance of
Collation
.array_filters (optional): A list of filters specifying which array elements an update should apply.
hint (optional): An index to use to support the query predicate specified either by its string name, or in the same format as passed to
create_index()
(e.g.[('field', ASCENDING)]
). This option is only supported on MongoDB 4.2 and above.session (optional): a
ClientSession
.let (optional): Map of parameter names and values. Values must be constant or closed expressions that do not reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. “$$var”).
comment (optional): A user-provided comment to attach to this command.
- Returns
An instance of
UpdateResult
.
Changed in version 4.1: Added
let
parameter. Addedcomment
parameter.Changed in version 3.11: Added
hint
parameter.Changed in version 3.9: Added the ability to accept a pipeline as the update.
Changed in version 3.6: Added
array_filters
andsession
parameters.Changed in version 3.4: Added the collation option.
Changed in version 3.2: Added bypass_document_validation support.
New in version 3.0.
- delete_one(filter: Mapping[str, Any], collation: Optional[Union[Mapping[str, Any], Collation]] = None, hint: Optional[Union[str, Sequence[Tuple[str, Union[int, str, Mapping[str, Any]]]]]] = None, session: Optional[ClientSession] = None, let: Optional[Mapping[str, Any]] = None, comment: Optional[Any] = None) pymongo.results.DeleteResult ¶
Delete a single document matching the filter.
>>> db.test.count_documents({'x': 1}) 3 >>> result = db.test.delete_one({'x': 1}) >>> result.deleted_count 1 >>> db.test.count_documents({'x': 1}) 2
- Parameters
filter: A query that matches the document to delete.
collation (optional): An instance of
Collation
.hint (optional): An index to use to support the query predicate specified either by its string name, or in the same format as passed to
create_index()
(e.g.[('field', ASCENDING)]
). This option is only supported on MongoDB 4.4 and above.session (optional): a
ClientSession
.let (optional): Map of parameter names and values. Values must be constant or closed expressions that do not reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. “$$var”).
comment (optional): A user-provided comment to attach to this command.
- Returns
An instance of
DeleteResult
.
Changed in version 4.1: Added
let
parameter. Addedcomment
parameter.Changed in version 3.11: Added
hint
parameter.Changed in version 3.6: Added
session
parameter.Changed in version 3.4: Added the collation option.
New in version 3.0.
- delete_many(filter: Mapping[str, Any], collation: Optional[Union[Mapping[str, Any], Collation]] = None, hint: Optional[Union[str, Sequence[Tuple[str, Union[int, str, Mapping[str, Any]]]]]] = None, session: Optional[ClientSession] = None, let: Optional[Mapping[str, Any]] = None, comment: Optional[Any] = None) pymongo.results.DeleteResult ¶
Delete one or more documents matching the filter.
>>> db.test.count_documents({'x': 1}) 3 >>> result = db.test.delete_many({'x': 1}) >>> result.deleted_count 3 >>> db.test.count_documents({'x': 1}) 0
- Parameters
filter: A query that matches the documents to delete.
collation (optional): An instance of
Collation
.hint (optional): An index to use to support the query predicate specified either by its string name, or in the same format as passed to
create_index()
(e.g.[('field', ASCENDING)]
). This option is only supported on MongoDB 4.4 and above.session (optional): a
ClientSession
.let (optional): Map of parameter names and values. Values must be constant or closed expressions that do not reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. “$$var”).
comment (optional): A user-provided comment to attach to this command.
- Returns
An instance of
DeleteResult
.
Changed in version 4.1: Added
let
parameter. Addedcomment
parameter.Changed in version 3.11: Added
hint
parameter.Changed in version 3.6: Added
session
parameter.Changed in version 3.4: Added the collation option.
New in version 3.0.
- aggregate(pipeline: Sequence[Mapping[str, Any]], session: Optional[ClientSession] = None, let: Optional[Mapping[str, Any]] = None, comment: Optional[Any] = None, **kwargs: Any) pymongo.command_cursor.CommandCursor[pymongo.typings._DocumentType] ¶
Perform an aggregation using the aggregation framework on this collection.
The
aggregate()
method obeys theread_preference
of thisCollection
, except when$out
or$merge
are used on MongoDB <5.0, in which casePRIMARY
is used.Note
This method does not support the ‘explain’ option. Please use
command()
instead. An example is included in the Aggregation Framework documentation.Note
The
write_concern
of this collection is automatically applied to this operation.- Parameters
pipeline: a list of aggregation pipeline stages
session (optional): a
ClientSession
.**kwargs (optional): extra aggregate command parameters.
All optional aggregate command parameters should be passed as keyword arguments to this method. Valid options include, but are not limited to:
allowDiskUse (bool): Enables writing to temporary files. When set to True, aggregation stages can write data to the _tmp subdirectory of the –dbpath directory. The default is False.
maxTimeMS (int): The maximum amount of time to allow the operation to run in milliseconds.
batchSize (int): The maximum number of documents to return per batch. Ignored if the connected mongod or mongos does not support returning aggregate results using a cursor.
collation (optional): An instance of
Collation
.let (dict): A dict of parameter names and values. Values must be constant or closed expressions that do not reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g.
"$$var"
). This option is only supported on MongoDB >= 5.0.comment (optional): A user-provided comment to attach to this command.
- Returns
A
CommandCursor
over the result set.
Changed in version 4.1: Added
comment
parameter. Addedlet
parameter. Support $merge and $out executing on secondaries according to the collection’sread_preference
.Changed in version 4.0: Removed the
useCursor
option.Changed in version 3.9: Apply this collection’s read concern to pipelines containing the $out stage when connected to MongoDB >= 4.2. Added support for the
$merge
pipeline stage. Aggregations that write always use read preferencePRIMARY
.Changed in version 3.6: Added the session parameter. Added the maxAwaitTimeMS option. Deprecated the useCursor option.
Changed in version 3.4: Apply this collection’s write concern automatically to this operation when connected to MongoDB >= 3.4. Support the collation option.
Changed in version 3.0: The
aggregate()
method always returns a CommandCursor. The pipeline argument must be a list.See also
- aggregate_raw_batches(pipeline: Sequence[Mapping[str, Any]], session: Optional[ClientSession] = None, comment: Optional[Any] = None, **kwargs: Any) pymongo.cursor.RawBatchCursor[pymongo.typings._DocumentType] ¶
Perform an aggregation and retrieve batches of raw BSON.
Similar to the
aggregate()
method but returns aRawBatchCursor
.This example demonstrates how to work with raw batches, but in practice raw batches should be passed to an external library that can decode BSON into another data type, rather than used with PyMongo’s
bson
module.>>> import bson >>> cursor = db.test.aggregate_raw_batches([ ... {'$project': {'x': {'$multiply': [2, '$x']}}}]) >>> for batch in cursor: ... print(bson.decode_all(batch))
Note
aggregate_raw_batches does not support auto encryption.
Changed in version 3.12: Added session support.
New in version 3.6.
- watch(pipeline: Optional[Sequence[Mapping[str, Any]]] = None, full_document: Optional[str] = None, resume_after: Optional[Mapping[str, Any]] = None, max_await_time_ms: Optional[int] = None, batch_size: Optional[int] = None, collation: Optional[Union[Mapping[str, Any], Collation]] = None, start_at_operation_time: Optional[bson.timestamp.Timestamp] = None, session: Optional[ClientSession] = None, start_after: Optional[Mapping[str, Any]] = None, comment: Optional[Any] = None, full_document_before_change: Optional[str] = None, show_expanded_events: Optional[bool] = None) pymongo.change_stream.CollectionChangeStream[pymongo.typings._DocumentType] ¶
Watch changes on this collection.
Performs an aggregation with an implicit initial
$changeStream
stage and returns aCollectionChangeStream
cursor which iterates over changes on this collection.with db.collection.watch() as stream: for change in stream: print(change)
The
CollectionChangeStream
iterable blocks until the next change document is returned or an error is raised. If thenext()
method encounters a network error when retrieving a batch from the server, it will automatically attempt to recreate the cursor such that no change events are missed. Any error encountered during the resume attempt indicates there may be an outage and will be raised.try: with db.collection.watch( [{'$match': {'operationType': 'insert'}}]) as stream: for insert_change in stream: print(insert_change) except pymongo.errors.PyMongoError: # The ChangeStream encountered an unrecoverable error or the # resume attempt failed to recreate the cursor. logging.error('...')
For a precise description of the resume process see the change streams specification.
Note
Using this helper method is preferred to directly calling
aggregate()
with a$changeStream
stage, for the purpose of supporting resumability.Warning
This Collection’s
read_concern
must beReadConcern("majority")
in order to use the$changeStream
stage.- Parameters
pipeline (optional): A list of aggregation pipeline stages to append to an initial
$changeStream
stage. Not all pipeline stages are valid after a$changeStream
stage, see the MongoDB documentation on change streams for the supported stages.full_document (optional): The fullDocument to pass as an option to the
$changeStream
stage. Allowed values: ‘updateLookup’, ‘whenAvailable’, ‘required’. When set to ‘updateLookup’, the change notification for partial updates will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred.full_document_before_change: Allowed values: ‘whenAvailable’ and ‘required’. Change events may now result in a ‘fullDocumentBeforeChange’ response field.
resume_after (optional): A resume token. If provided, the change stream will start returning changes that occur directly after the operation specified in the resume token. A resume token is the _id value of a change document.
max_await_time_ms (optional): The maximum time in milliseconds for the server to wait for changes before responding to a getMore operation.
batch_size (optional): The maximum number of documents to return per batch.
collation (optional): The
Collation
to use for the aggregation.start_at_operation_time (optional): If provided, the resulting change stream will only return changes that occurred at or after the specified
Timestamp
. Requires MongoDB >= 4.0.session (optional): a
ClientSession
.start_after (optional): The same as resume_after except that start_after can resume notifications after an invalidate event. This option and resume_after are mutually exclusive.
comment (optional): A user-provided comment to attach to this command.
show_expanded_events (optional): Include expanded events such as DDL events like dropIndexes.
- Returns
A
CollectionChangeStream
cursor.
Changed in version 4.3: Added show_expanded_events parameter.
Changed in version 4.2: Added
full_document_before_change
parameter.Changed in version 4.1: Added
comment
parameter.Changed in version 3.9: Added the
start_after
parameter.Changed in version 3.7: Added the
start_at_operation_time
parameter.New in version 3.6.
See also
The MongoDB documentation on changeStreams.
- find(filter=None, projection=None, skip=0, limit=0, no_cursor_timeout=False, cursor_type=CursorType.NON_TAILABLE, sort=None, allow_partial_results=False, oplog_replay=False, batch_size=0, collation=None, hint=None, max_scan=None, max_time_ms=None, max=None, min=None, return_key=False, show_record_id=False, snapshot=False, comment=None, session=None, allow_disk_use=None)¶
Query the database.
The filter argument is a query document that all results must match. For example:
>>> db.test.find({"hello": "world"})
only matches documents that have a key “hello” with value “world”. Matches can have other keys in addition to “hello”. The projection argument is used to specify a subset of fields that should be included in the result documents. By limiting results to a certain subset of fields you can cut down on network traffic and decoding time.
Raises
TypeError
if any of the arguments are of improper type. Returns an instance ofCursor
corresponding to this query.The
find()
method obeys theread_preference
of thisCollection
.- Parameters
filter (optional): A query document that selects which documents to include in the result set. Can be an empty document to include all documents.
projection (optional): a list of field names that should be returned in the result set or a dict specifying the fields to include or exclude. If projection is a list “_id” will always be returned. Use a dict to exclude fields from the result (e.g. projection={‘_id’: False}).
session (optional): a
ClientSession
.skip (optional): the number of documents to omit (from the start of the result set) when returning the results
limit (optional): the maximum number of results to return. A limit of 0 (the default) is equivalent to setting no limit.
no_cursor_timeout (optional): if False (the default), any returned cursor is closed by the server after 10 minutes of inactivity. If set to True, the returned cursor will never time out on the server. Care should be taken to ensure that cursors with no_cursor_timeout turned on are properly closed.
cursor_type (optional): the type of cursor to return. The valid options are defined by
CursorType
:NON_TAILABLE
- the result of this find call will return a standard cursor over the result set.TAILABLE
- the result of this find call will be a tailable cursor - tailable cursors are only for use with capped collections. They are not closed when the last data is retrieved but are kept open and the cursor location marks the final document position. If more data is received iteration of the cursor will continue from the last document received. For details, see the tailable cursor documentation.TAILABLE_AWAIT
- the result of this find call will be a tailable cursor with the await flag set. The server will wait for a few seconds after returning the full result set so that it can capture and return additional data added during the query.EXHAUST
- the result of this find call will be an exhaust cursor. MongoDB will stream batched results to the client without waiting for the client to request each batch, reducing latency. See notes on compatibility below.
sort (optional): a list of (key, direction) pairs specifying the sort order for this query. See
sort()
for details.allow_partial_results (optional): if True, mongos will return partial results if some shards are down instead of returning an error.
oplog_replay (optional): DEPRECATED - if True, set the oplogReplay query flag. Default: False.
batch_size (optional): Limits the number of documents returned in a single batch.
collation (optional): An instance of
Collation
.return_key (optional): If True, return only the index keys in each document.
show_record_id (optional): If True, adds a field
$recordId
in each document with the storage engine’s internal record identifier.snapshot (optional): DEPRECATED - If True, prevents the cursor from returning a document more than once because of an intervening write operation.
hint (optional): An index, in the same format as passed to
create_index()
(e.g.[('field', ASCENDING)]
). Pass this as an alternative to callinghint()
on the cursor to tell Mongo the proper index to use for the query.max_time_ms (optional): Specifies a time limit for a query operation. If the specified time is exceeded, the operation will be aborted and
ExecutionTimeout
is raised. Pass this as an alternative to callingmax_time_ms()
on the cursor.max_scan (optional): DEPRECATED - The maximum number of documents to scan. Pass this as an alternative to calling
max_scan()
on the cursor.min (optional): A list of field, limit pairs specifying the inclusive lower bound for all keys of a specific index in order. Pass this as an alternative to calling
min()
on the cursor.hint
must also be passed to ensure the query utilizes the correct index.max (optional): A list of field, limit pairs specifying the exclusive upper bound for all keys of a specific index in order. Pass this as an alternative to calling
max()
on the cursor.hint
must also be passed to ensure the query utilizes the correct index.comment (optional): A string to attach to the query to help interpret and trace the operation in the server logs and in profile data. Pass this as an alternative to calling
comment()
on the cursor.allow_disk_use (optional): if True, MongoDB may use temporary disk files to store data exceeding the system memory limit while processing a blocking sort operation. The option has no effect if MongoDB can satisfy the specified sort using an index, or if the blocking sort requires less memory than the 100 MiB limit. This option is only supported on MongoDB 4.4 and above.
Note
There are a number of caveats to using
EXHAUST
as cursor_type:The limit option can not be used with an exhaust cursor.
Exhaust cursors are not supported by mongos and can not be used with a sharded cluster.
A
Cursor
instance created with theEXHAUST
cursor_type requires an exclusivesocket
connection to MongoDB. If theCursor
is discarded without being completely iterated the underlyingsocket
connection will be closed and discarded without being returned to the connection pool.
Changed in version 4.0: Removed the
modifiers
option. Empty projections (eg {} or []) are passed to the server as-is, rather than the previous behavior which substituted in a projection of{"_id": 1}
. This means that an empty projection will now return the entire document, not just the"_id"
field.Changed in version 3.11: Added the
allow_disk_use
option. Deprecated theoplog_replay
option. Support for this option is deprecated in MongoDB 4.4. The query engine now automatically optimizes queries against the oplog without requiring this option to be set.Changed in version 3.7: Deprecated the
snapshot
option, which is deprecated in MongoDB 3.6 and removed in MongoDB 4.0. Deprecated themax_scan
option. Support for this option is deprecated in MongoDB 4.0. Usemax_time_ms
instead to limit server-side execution time.Changed in version 3.6: Added
session
parameter.Changed in version 3.5: Added the options
return_key
,show_record_id
,snapshot
,hint
,max_time_ms
,max_scan
,min
,max
, andcomment
. Deprecated themodifiers
option.Changed in version 3.4: Added support for the
collation
option.Changed in version 3.0: Changed the parameter names
spec
,fields
,timeout
, andpartial
tofilter
,projection
,no_cursor_timeout
, andallow_partial_results
respectively. Added thecursor_type
,oplog_replay
, andmodifiers
options. Removed thenetwork_timeout
,read_preference
,tag_sets
,secondary_acceptable_latency_ms
,max_scan
,snapshot
,tailable
,await_data
,exhaust
,as_class
, and slave_okay parameters. Removedcompile_re
option: PyMongo now always represents BSON regular expressions asRegex
objects. Usetry_compile()
to attempt to convert from a BSON regular expression to a Python regular expression object. Soft deprecated themanipulate
option.See also
The MongoDB documentation on find.
- find_raw_batches(filter=None, projection=None, skip=0, limit=0, no_cursor_timeout=False, cursor_type=CursorType.NON_TAILABLE, sort=None, allow_partial_results=False, oplog_replay=False, batch_size=0, collation=None, hint=None, max_scan=None, max_time_ms=None, max=None, min=None, return_key=False, show_record_id=False, snapshot=False, comment=None, session=None, allow_disk_use=None)¶
Query the database and retrieve batches of raw BSON.
Similar to the
find()
method but returns aRawBatchCursor
.This example demonstrates how to work with raw batches, but in practice raw batches should be passed to an external library that can decode BSON into another data type, rather than used with PyMongo’s
bson
module.>>> import bson >>> cursor = db.test.find_raw_batches() >>> for batch in cursor: ... print(bson.decode_all(batch))
Note
find_raw_batches does not support auto encryption.
Changed in version 3.12: Instead of ignoring the user-specified read concern, this method now sends it to the server when connected to MongoDB 3.6+.
Added session support.
New in version 3.6.
- find_one(filter=None, *args, **kwargs)¶
Get a single document from the database.
All arguments to
find()
are also valid arguments forfind_one()
, although any limit argument will be ignored. Returns a single document, orNone
if no matching document is found.The
find_one()
method obeys theread_preference
of thisCollection
.- Parameters
filter (optional): a dictionary specifying the query to be performed OR any other type to be used as the value for a query for
"_id"
.*args (optional): any additional positional arguments are the same as the arguments to
find()
.**kwargs (optional): any additional keyword arguments are the same as the arguments to
find()
.>>> collection.find_one(max_time_ms=100)
- find_one_and_delete(filter: Mapping[str, Any], projection: Optional[Union[Mapping[str, Any], Iterable[str]]] = None, sort: Optional[Sequence[Tuple[str, Union[int, str, Mapping[str, Any]]]]] = None, hint: Optional[Union[str, Sequence[Tuple[str, Union[int, str, Mapping[str, Any]]]]]] = None, session: Optional[ClientSession] = None, let: Optional[Mapping[str, Any]] = None, comment: Optional[Any] = None, **kwargs: Any) pymongo.typings._DocumentType ¶
Finds a single document and deletes it, returning the document.
>>> db.test.count_documents({'x': 1}) 2 >>> db.test.find_one_and_delete({'x': 1}) {'x': 1, '_id': ObjectId('54f4e12bfba5220aa4d6dee8')} >>> db.test.count_documents({'x': 1}) 1
If multiple documents match filter, a sort can be applied.
>>> for doc in db.test.find({'x': 1}): ... print(doc) ... {'x': 1, '_id': 0} {'x': 1, '_id': 1} {'x': 1, '_id': 2} >>> db.test.find_one_and_delete( ... {'x': 1}, sort=[('_id', pymongo.DESCENDING)]) {'x': 1, '_id': 2}
The projection option can be used to limit the fields returned.
>>> db.test.find_one_and_delete({'x': 1}, projection={'_id': False}) {'x': 1}
- Parameters
filter: A query that matches the document to delete.
projection (optional): a list of field names that should be returned in the result document or a mapping specifying the fields to include or exclude. If projection is a list “_id” will always be returned. Use a mapping to exclude fields from the result (e.g. projection={‘_id’: False}).
sort (optional): a list of (key, direction) pairs specifying the sort order for the query. If multiple documents match the query, they are sorted and the first is deleted.
hint (optional): An index to use to support the query predicate specified either by its string name, or in the same format as passed to
create_index()
(e.g.[('field', ASCENDING)]
). This option is only supported on MongoDB 4.4 and above.session (optional): a
ClientSession
.let (optional): Map of parameter names and values. Values must be constant or closed expressions that do not reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. “$$var”).
comment (optional): A user-provided comment to attach to this command.
**kwargs (optional): additional command arguments can be passed as keyword arguments (for example maxTimeMS can be used with recent server versions).
Changed in version 4.1: Added
let
parameter.Changed in version 3.11: Added
hint
parameter.Changed in version 3.6: Added
session
parameter.Changed in version 3.2: Respects write concern.
Warning
Starting in PyMongo 3.2, this command uses the
WriteConcern
of thisCollection
when connected to MongoDB >= 3.2. Note that using an elevated write concern with this command may be slower compared to using the default write concern.Changed in version 3.4: Added the collation option.
New in version 3.0.
- find_one_and_replace(filter, replacement, projection=None, sort=None, return_document=ReturnDocument.BEFORE, hint=None, session=None, **kwargs)¶
Finds a single document and replaces it, returning either the original or the replaced document.
The
find_one_and_replace()
method differs fromfind_one_and_update()
by replacing the document matched by filter, rather than modifying the existing document.>>> for doc in db.test.find({}): ... print(doc) ... {'x': 1, '_id': 0} {'x': 1, '_id': 1} {'x': 1, '_id': 2} >>> db.test.find_one_and_replace({'x': 1}, {'y': 1}) {'x': 1, '_id': 0} >>> for doc in db.test.find({}): ... print(doc) ... {'y': 1, '_id': 0} {'x': 1, '_id': 1} {'x': 1, '_id': 2}
- Parameters
filter: A query that matches the document to replace.
replacement: The replacement document.
projection (optional): A list of field names that should be returned in the result document or a mapping specifying the fields to include or exclude. If projection is a list “_id” will always be returned. Use a mapping to exclude fields from the result (e.g. projection={‘_id’: False}).
sort (optional): a list of (key, direction) pairs specifying the sort order for the query. If multiple documents match the query, they are sorted and the first is replaced.
upsert (optional): When
True
, inserts a new document if no document matches the query. Defaults toFalse
.return_document: If
ReturnDocument.BEFORE
(the default), returns the original document before it was replaced, orNone
if no document matches. IfReturnDocument.AFTER
, returns the replaced or inserted document.hint (optional): An index to use to support the query predicate specified either by its string name, or in the same format as passed to
create_index()
(e.g.[('field', ASCENDING)]
). This option is only supported on MongoDB 4.4 and above.session (optional): a
ClientSession
.let (optional): Map of parameter names and values. Values must be constant or closed expressions that do not reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. “$$var”).
comment (optional): A user-provided comment to attach to this command.
**kwargs (optional): additional command arguments can be passed as keyword arguments (for example maxTimeMS can be used with recent server versions).
Changed in version 4.1: Added
let
parameter.Changed in version 3.11: Added the
hint
option.Changed in version 3.6: Added
session
parameter.Changed in version 3.4: Added the
collation
option.Changed in version 3.2: Respects write concern.
Warning
Starting in PyMongo 3.2, this command uses the
WriteConcern
of thisCollection
when connected to MongoDB >= 3.2. Note that using an elevated write concern with this command may be slower compared to using the default write concern.New in version 3.0.
- find_one_and_update(filter, update, projection=None, sort=None, return_document=ReturnDocument.BEFORE, array_filters=None, hint=None, session=None, **kwargs)¶
Finds a single document and updates it, returning either the original or the updated document.
>>> db.test.find_one_and_update( ... {'_id': 665}, {'$inc': {'count': 1}, '$set': {'done': True}}) {'_id': 665, 'done': False, 'count': 25}}
Returns
None
if no document matches the filter.>>> db.test.find_one_and_update( ... {'_exists': False}, {'$inc': {'count': 1}})
When the filter matches, by default
find_one_and_update()
returns the original version of the document before the update was applied. To return the updated (or inserted in the case of upsert) version of the document instead, use the return_document option.>>> from pymongo import ReturnDocument >>> db.example.find_one_and_update( ... {'_id': 'userid'}, ... {'$inc': {'seq': 1}}, ... return_document=ReturnDocument.AFTER) {'_id': 'userid', 'seq': 1}
You can limit the fields returned with the projection option.
>>> db.example.find_one_and_update( ... {'_id': 'userid'}, ... {'$inc': {'seq': 1}}, ... projection={'seq': True, '_id': False}, ... return_document=ReturnDocument.AFTER) {'seq': 2}
The upsert option can be used to create the document if it doesn’t already exist.
>>> db.example.delete_many({}).deleted_count 1 >>> db.example.find_one_and_update( ... {'_id': 'userid'}, ... {'$inc': {'seq': 1}}, ... projection={'seq': True, '_id': False}, ... upsert=True, ... return_document=ReturnDocument.AFTER) {'seq': 1}
If multiple documents match filter, a sort can be applied.
>>> for doc in db.test.find({'done': True}): ... print(doc) ... {'_id': 665, 'done': True, 'result': {'count': 26}} {'_id': 701, 'done': True, 'result': {'count': 17}} >>> db.test.find_one_and_update( ... {'done': True}, ... {'$set': {'final': True}}, ... sort=[('_id', pymongo.DESCENDING)]) {'_id': 701, 'done': True, 'result': {'count': 17}}
- Parameters
filter: A query that matches the document to update.
update: The update operations to apply.
projection (optional): A list of field names that should be returned in the result document or a mapping specifying the fields to include or exclude. If projection is a list “_id” will always be returned. Use a dict to exclude fields from the result (e.g. projection={‘_id’: False}).
sort (optional): a list of (key, direction) pairs specifying the sort order for the query. If multiple documents match the query, they are sorted and the first is updated.
upsert (optional): When
True
, inserts a new document if no document matches the query. Defaults toFalse
.return_document: If
ReturnDocument.BEFORE
(the default), returns the original document before it was updated. IfReturnDocument.AFTER
, returns the updated or inserted document.array_filters (optional): A list of filters specifying which array elements an update should apply.
hint (optional): An index to use to support the query predicate specified either by its string name, or in the same format as passed to
create_index()
(e.g.[('field', ASCENDING)]
). This option is only supported on MongoDB 4.4 and above.session (optional): a
ClientSession
.let (optional): Map of parameter names and values. Values must be constant or closed expressions that do not reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. “$$var”).
comment (optional): A user-provided comment to attach to this command.
**kwargs (optional): additional command arguments can be passed as keyword arguments (for example maxTimeMS can be used with recent server versions).
Changed in version 3.11: Added the
hint
option.Changed in version 3.9: Added the ability to accept a pipeline as the
update
.Changed in version 3.6: Added the
array_filters
andsession
options.Changed in version 3.4: Added the
collation
option.Changed in version 3.2: Respects write concern.
Warning
Starting in PyMongo 3.2, this command uses the
WriteConcern
of thisCollection
when connected to MongoDB >= 3.2. Note that using an elevated write concern with this command may be slower compared to using the default write concern.New in version 3.0.
- count_documents(filter: Mapping[str, Any], session: Optional[ClientSession] = None, comment: Optional[Any] = None, **kwargs: Any) int ¶
Count the number of documents in this collection.
Note
For a fast count of the total documents in a collection see
estimated_document_count()
.The
count_documents()
method is supported in a transaction.All optional parameters should be passed as keyword arguments to this method. Valid options include:
skip (int): The number of matching documents to skip before returning results.
limit (int): The maximum number of documents to count. Must be a positive integer. If not provided, no limit is imposed.
maxTimeMS (int): The maximum amount of time to allow this operation to run, in milliseconds.
collation (optional): An instance of
Collation
.hint (string or list of tuples): The index to use. Specify either the index name as a string or the index specification as a list of tuples (e.g. [(‘a’, pymongo.ASCENDING), (‘b’, pymongo.ASCENDING)]).
The
count_documents()
method obeys theread_preference
of thisCollection
.Note
When migrating from
count()
tocount_documents()
the following query operators must be replaced:Operator
Replacement
$where
$near
$geoWithin with $center
$nearSphere
$geoWithin with $centerSphere
- Parameters
filter (required): A query document that selects which documents to count in the collection. Can be an empty document to count all documents.
session (optional): a
ClientSession
.comment (optional): A user-provided comment to attach to this command.
**kwargs (optional): See list of options above.
New in version 3.7.
- estimated_document_count(comment: Optional[Any] = None, **kwargs: Any) int ¶
Get an estimate of the number of documents in this collection using collection metadata.
The
estimated_document_count()
method is not supported in a transaction.All optional parameters should be passed as keyword arguments to this method. Valid options include:
maxTimeMS (int): The maximum amount of time to allow this operation to run, in milliseconds.
- Parameters
comment (optional): A user-provided comment to attach to this command.
**kwargs (optional): See list of options above.
Changed in version 4.2: This method now always uses the count command. Due to an oversight in versions 5.0.0-5.0.8 of MongoDB, the count command was not included in V1 of the MongoDB Stable API. Users of the Stable API with estimated_document_count are recommended to upgrade their server version to 5.0.9+ or set
pymongo.server_api.ServerApi.strict
toFalse
to avoid encountering errors.New in version 3.7.
- distinct(key: str, filter: Optional[Mapping[str, Any]] = None, session: Optional[ClientSession] = None, comment: Optional[Any] = None, **kwargs: Any) List ¶
Get a list of distinct values for key among all documents in this collection.
Raises
TypeError
if key is not an instance ofbasestring
(str
in python 3).All optional distinct parameters should be passed as keyword arguments to this method. Valid options include:
maxTimeMS (int): The maximum amount of time to allow the count command to run, in milliseconds.
collation (optional): An instance of
Collation
.
The
distinct()
method obeys theread_preference
of thisCollection
.- Parameters
key: name of the field for which we want to get the distinct values
filter (optional): A query document that specifies the documents from which to retrieve the distinct values.
session (optional): a
ClientSession
.comment (optional): A user-provided comment to attach to this command.
**kwargs (optional): See list of options above.
Changed in version 3.6: Added
session
parameter.Changed in version 3.4: Support the collation option.
- create_index(keys: Union[str, Sequence[Tuple[str, Union[int, str, Mapping[str, Any]]]]], session: Optional[ClientSession] = None, comment: Optional[Any] = None, **kwargs: Any) str ¶
Creates an index on this collection.
Takes either a single key or a list of (key, direction) pairs. The key(s) must be an instance of
basestring
(str
in python 3), and the direction(s) must be one of (ASCENDING
,DESCENDING
,GEO2D
,GEOSPHERE
,HASHED
,TEXT
).To create a single key ascending index on the key
'mike'
we just use a string argument:>>> my_collection.create_index("mike")
For a compound index on
'mike'
descending and'eliot'
ascending we need to use a list of tuples:>>> my_collection.create_index([("mike", pymongo.DESCENDING), ... ("eliot", pymongo.ASCENDING)])
All optional index creation parameters should be passed as keyword arguments to this method. For example:
>>> my_collection.create_index([("mike", pymongo.DESCENDING)], ... background=True)
Valid options include, but are not limited to:
name: custom name to use for this index - if none is given, a name will be generated.
unique: if
True
, creates a uniqueness constraint on the index.background: if
True
, this index should be created in the background.sparse: if
True
, omit from the index any documents that lack the indexed field.bucketSize: for use with geoHaystack indexes. Number of documents to group together within a certain proximity to a given longitude and latitude.
min: minimum value for keys in a
GEO2D
index.max: maximum value for keys in a
GEO2D
index.expireAfterSeconds: <int> Used to create an expiring (TTL) collection. MongoDB will automatically delete documents from this collection after <int> seconds. The indexed field must be a UTC datetime or the data will not expire.
partialFilterExpression: A document that specifies a filter for a partial index.
collation (optional): An instance of
Collation
.wildcardProjection: Allows users to include or exclude specific field paths from a wildcard index using the {“$**” : 1} key pattern. Requires MongoDB >= 4.2.
hidden: if
True
, this index will be hidden from the query planner and will not be evaluated as part of query plan selection. Requires MongoDB >= 4.4.
See the MongoDB documentation for a full list of supported options by server version.
Warning
dropDups is not supported by MongoDB 3.0 or newer. The option is silently ignored by the server and unique index builds using the option will fail if a duplicate value is detected.
Note
The
write_concern
of this collection is automatically applied to this operation.- Parameters
keys: a single key or a list of (key, direction) pairs specifying the index to create
session (optional): a
ClientSession
. argumentscomment (optional): A user-provided comment to attach to this command.
**kwargs (optional): any additional index creation options (see the above list) should be passed as keyword
Changed in version 4.1: Added
comment
parameter.Changed in version 3.11: Added the
hidden
option.Changed in version 3.6: Added
session
parameter. Added support for passing maxTimeMS in kwargs.Changed in version 3.4: Apply this collection’s write concern automatically to this operation when connected to MongoDB >= 3.4. Support the collation option.
Changed in version 3.2: Added partialFilterExpression to support partial indexes.
Changed in version 3.0: Renamed key_or_list to keys. Removed the cache_for option.
create_index()
no longer caches index names. Removed support for the drop_dups and bucket_size aliases.See also
The MongoDB documentation on indexes.
- create_indexes(indexes: Sequence[pymongo.operations.IndexModel], session: Optional[ClientSession] = None, comment: Optional[Any] = None, **kwargs: Any) List[str] ¶
Create one or more indexes on this collection.
>>> from pymongo import IndexModel, ASCENDING, DESCENDING >>> index1 = IndexModel([("hello", DESCENDING), ... ("world", ASCENDING)], name="hello_world") >>> index2 = IndexModel([("goodbye", DESCENDING)]) >>> db.test.create_indexes([index1, index2]) ["hello_world", "goodbye_-1"]
- Parameters
indexes: A list of
IndexModel
instances.session (optional): a
ClientSession
.comment (optional): A user-provided comment to attach to this command.
**kwargs (optional): optional arguments to the createIndexes command (like maxTimeMS) can be passed as keyword arguments.
Note
The
write_concern
of this collection is automatically applied to this operation.Changed in version 3.6: Added
session
parameter. Added support for arbitrary keyword arguments.Changed in version 3.4: Apply this collection’s write concern automatically to this operation when connected to MongoDB >= 3.4.
New in version 3.0.
- drop_index(index_or_name: Union[str, Sequence[Tuple[str, Union[int, str, Mapping[str, Any]]]]], session: Optional[ClientSession] = None, comment: Optional[Any] = None, **kwargs: Any) None ¶
Drops the specified index on this collection.
Can be used on non-existant collections or collections with no indexes. Raises OperationFailure on an error (e.g. trying to drop an index that does not exist). index_or_name can be either an index name (as returned by create_index), or an index specifier (as passed to create_index). An index specifier should be a list of (key, direction) pairs. Raises TypeError if index is not an instance of (str, unicode, list).
Warning
if a custom name was used on index creation (by passing the name parameter to
create_index()
) the index must be dropped by name.- Parameters
index_or_name: index (or name of index) to drop
session (optional): a
ClientSession
.comment (optional): A user-provided comment to attach to this command.
**kwargs (optional): optional arguments to the createIndexes command (like maxTimeMS) can be passed as keyword arguments.
Note
The
write_concern
of this collection is automatically applied to this operation.Changed in version 3.6: Added
session
parameter. Added support for arbitrary keyword arguments.Changed in version 3.4: Apply this collection’s write concern automatically to this operation when connected to MongoDB >= 3.4.
- drop_indexes(session: Optional[ClientSession] = None, comment: Optional[Any] = None, **kwargs: Any) None ¶
Drops all indexes on this collection.
Can be used on non-existant collections or collections with no indexes. Raises OperationFailure on an error.
- Parameters
session (optional): a
ClientSession
. argumentscomment (optional): A user-provided comment to attach to this command.
**kwargs (optional): optional arguments to the createIndexes command (like maxTimeMS) can be passed as keyword arguments.
Note
The
write_concern
of this collection is automatically applied to this operation.Changed in version 3.6: Added
session
parameter. Added support for arbitrary keyword arguments.Changed in version 3.4: Apply this collection’s write concern automatically to this operation when connected to MongoDB >= 3.4.
- list_indexes(session: Optional[ClientSession] = None, comment: Optional[Any] = None) pymongo.command_cursor.CommandCursor[MutableMapping[str, Any]] ¶
Get a cursor over the index documents for this collection.
>>> for index in db.test.list_indexes(): ... print(index) ... SON([('v', 2), ('key', SON([('_id', 1)])), ('name', '_id_')])
- Parameters
session (optional): a
ClientSession
.comment (optional): A user-provided comment to attach to this command.
- Returns
An instance of
CommandCursor
.
Changed in version 4.1: Added
comment
parameter.Changed in version 3.6: Added
session
parameter.New in version 3.0.
- index_information(session: Optional[ClientSession] = None, comment: Optional[Any] = None) MutableMapping[str, Any] ¶
Get information on this collection’s indexes.
Returns a dictionary where the keys are index names (as returned by create_index()) and the values are dictionaries containing information about each index. The dictionary is guaranteed to contain at least a single key,
"key"
which is a list of (key, direction) pairs specifying the index (as passed to create_index()). It will also contain any other metadata about the indexes, except for the"ns"
and"name"
keys, which are cleaned. Example output might look like this:>>> db.test.create_index("x", unique=True) 'x_1' >>> db.test.index_information() {'_id_': {'key': [('_id', 1)]}, 'x_1': {'unique': True, 'key': [('x', 1)]}}
- Parameters
session (optional): a
ClientSession
.comment (optional): A user-provided comment to attach to this command.
Changed in version 4.1: Added
comment
parameter.Changed in version 3.6: Added
session
parameter.
- drop(session: Optional[ClientSession] = None, comment: Optional[Any] = None, encrypted_fields: Optional[Mapping[str, Any]] = None) None ¶
Alias for
drop_collection()
.- Parameters
session (optional): a
ClientSession
.comment (optional): A user-provided comment to attach to this command.
encrypted_fields: (BETA) Document that describes the encrypted fields for Queryable Encryption.
The following two calls are equivalent:
>>> db.foo.drop() >>> db.drop_collection("foo")
Changed in version 4.2: Added
encrypted_fields
parameter.Changed in version 4.1: Added
comment
parameter.Changed in version 3.7:
drop()
now respects thisCollection
’swrite_concern
.Changed in version 3.6: Added
session
parameter.
- rename(new_name: str, session: Optional[ClientSession] = None, comment: Optional[Any] = None, **kwargs: Any) MutableMapping[str, Any] ¶
Rename this collection.
If operating in auth mode, client must be authorized as an admin to perform this operation. Raises
TypeError
if new_name is not an instance ofbasestring
(str
in python 3). RaisesInvalidName
if new_name is not a valid collection name.- Parameters
new_name: new name for this collection
session (optional): a
ClientSession
.comment (optional): A user-provided comment to attach to this command.
**kwargs (optional): additional arguments to the rename command may be passed as keyword arguments to this helper method (i.e.
dropTarget=True
)
Note
The
write_concern
of this collection is automatically applied to this operation.Changed in version 3.6: Added
session
parameter.Changed in version 3.4: Apply this collection’s write concern automatically to this operation when connected to MongoDB >= 3.4.
- options(session: Optional[ClientSession] = None, comment: Optional[Any] = None) MutableMapping[str, Any] ¶
Get the options set on this collection.
Returns a dictionary of options and their values - see
create_collection()
for more information on the possible options. Returns an empty dictionary if the collection has not been created yet.- Parameters
session (optional): a
ClientSession
.comment (optional): A user-provided comment to attach to this command.
Changed in version 3.6: Added
session
parameter.