collection – Collection level operations (original) (raw)

Collection level utilities for Mongo.

class pymongo.asynchronous.collection.ReturnDocument

An enum used withfind_one_and_replace() andfind_one_and_update().

class pymongo.asynchronous.collection.AsyncCollection(database, name, create=False, **kwargs)

Get / create an asynchronous Mongo collection.

Raises TypeError if name is not an instance ofstr. Raises InvalidName 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, a create command will be sent, using session if specified. Otherwise, a create command will not be sent and the collection will be created implicitly on first use. The optional session argument is only used for the createcommand, it is not associated with the collection afterward.

Parameters:

Changed in version 4.2: Added the clusteredIndex and encryptedFields 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 thePyMongo 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.AsyncCollection no longer returns an instance of AsyncCollection for attribute names with leading underscores. You must use dict-style lookups instead::

collection[‘__my_collection__’]

Not:

collection.__my_collection__

c[name] || c.name

Get the name sub-collection of AsyncCollection c.

Raises InvalidName if an invalid collection name is used.

full_name

The full name of this AsyncCollection.

The full name is of the form database_name.collection_name.

name

The name of this AsyncCollection.

database

The AsyncDatabase that thisAsyncCollection is a part of.

codec_options

Read only access to the CodecOptionsof 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 WriteConcernof this instance.

Changed in version 3.0: The write_concern attribute is now read only.

read_concern

Read only access to the ReadConcernof this instance.

Added in version 3.2.

with_options(codec_options: None = None, read_preference: _ServerMode | None = None, write_concern: WriteConcern | None = None, read_concern: ReadConcern | None = None) → AsyncCollection[_DocumentType]

with_options(codec_options: bson.CodecOptions[_DocumentTypeArg], read_preference: _ServerMode | None = None, write_concern: WriteConcern | None = None, read_concern: ReadConcern | None = None) → AsyncCollection[_DocumentTypeArg]

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:

async bulk_write(requests, ordered=True, bypass_document_validation=None, session=None, comment=None, let=None)

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).

async 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 = await db.test.bulk_write(requests) result.inserted_count 1 result.deleted_count 1 result.modified_count 0 result.upserted_ids {2: ObjectId('54f62ee28891e756a6e1abd5')} async for doc in db.test.find({}): ... print(doc) ... {'x': 1, '_id': ObjectId('54f62e60fba5226811f634f0')} {'y': 1, '_id': ObjectId('54f62ee2fba5226811f634f1')} {'z': 1, '_id': ObjectId('54f62ee28891e756a6e1abd5')}

Parameters:

Returns:

An instance of BulkWriteResult.

Return type:

BulkWriteResult

Note

bypass_document_validation requires server version>= 3.2

Changed in version 4.1: Added comment parameter. Added let parameter.

Changed in version 3.6: Added session parameter.

Changed in version 3.2: Added bypass_document_validation support

Added in version 3.0.

async insert_one(document, bypass_document_validation=None, session=None, comment=None)

Insert a single document.

await db.test.count_documents({'x': 1}) 0 result = await db.test.insert_one({'x': 1}) result.inserted_id ObjectId('54f112defba522406c9cc208') await db.test.find_one({'x': 1}) {'x': 1, '_id': ObjectId('54f112defba522406c9cc208')}

Parameters:

Returns:

Return type:

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

Added in version 3.0.

async insert_many(documents, ordered=True, bypass_document_validation=None, session=None, comment=None)

Insert an iterable of documents.

await db.test.count_documents({}) 0 result = await db.test.insert_many([{'x': i} for i in range(2)]) await result.inserted_ids [ObjectId('54f113fffba522406c9cc20e'), ObjectId('54f113fffba522406c9cc20f')] await db.test.count_documents({}) 2

Parameters:

Returns:

An instance of InsertManyResult.

Return type:

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

Added in version 3.0.

async replace_one(filter, replacement, upsert=False, bypass_document_validation=None, collation=None, hint=None, session=None, let=None, sort=None, comment=None)

Replace a single document matching the filter.

async for doc in db.test.find({}): ... print(doc) ... {'x': 1, '_id': ObjectId('54f4c5befba5220aa4d6dee7')} result = await db.test.replace_one({'x': 1}, {'y': 1}) result.matched_count 1 result.modified_count 1 async 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 = await db.test.replace_one({'x': 1}, {'x': 1}, True) result.matched_count 0 result.modified_count 0 result.upserted_id ObjectId('54f11e5c8891e756a6e1abd4') await db.test.find_one({'x': 1}) {'x': 1, '_id': ObjectId('54f11e5c8891e756a6e1abd4')}

Parameters:

Returns:

Return type:

UpdateResult

Changed in version 4.11: Added sort parameter.

Changed in version 4.1: Added let parameter. Added comment 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.

Added in version 3.0.

async update_one(filter, update, upsert=False, bypass_document_validation=None, collation=None, array_filters=None, hint=None, session=None, let=None, sort=None, comment=None)

Update a single document matching the filter.

async for doc in db.test.find(): ... print(doc) ... {'x': 1, '_id': 0} {'x': 1, '_id': 1} {'x': 1, '_id': 2} result = await db.test.update_one({'x': 1}, {'$inc': {'x': 3}}) result.matched_count 1 result.modified_count 1 async 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 = await db.test.update_one({'x': -10}, {'$inc': {'x': 3}}, upsert=True) result.matched_count 0 result.modified_count 0 result.upserted_id ObjectId('626a678eeaa80587d4bb3fb7') await db.test.find_one(result.upserted_id) {'_id': ObjectId('626a678eeaa80587d4bb3fb7'), 'x': -7}

Parameters:

Returns:

Return type:

UpdateResult

Changed in version 4.11: Added sort parameter.

Changed in version 4.1: Added let parameter. Added comment 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 and session parameters.

Changed in version 3.4: Added the collation option.

Changed in version 3.2: Added bypass_document_validation support.

Added in version 3.0.

async update_many(filter, update, upsert=False, array_filters=None, bypass_document_validation=None, collation=None, hint=None, session=None, let=None, comment=None)

Update one or more documents that match the filter.

async for doc in db.test.find(): ... print(doc) ... {'x': 1, '_id': 0} {'x': 1, '_id': 1} {'x': 1, '_id': 2} result = await db.test.update_many({'x': 1}, {'$inc': {'x': 3}}) result.matched_count 3 result.modified_count 3 async for doc in db.test.find(): ... print(doc) ... {'x': 4, '_id': 0} {'x': 4, '_id': 1} {'x': 4, '_id': 2}

Parameters:

Returns:

Return type:

UpdateResult

Changed in version 4.1: Added let parameter. Added comment 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 and session parameters.

Changed in version 3.4: Added the collation option.

Changed in version 3.2: Added bypass_document_validation support.

Added in version 3.0.

async delete_one(filter, collation=None, hint=None, session=None, let=None, comment=None)

Delete a single document matching the filter.

await db.test.count_documents({'x': 1}) 3 result = await db.test.delete_one({'x': 1}) result.deleted_count 1 await db.test.count_documents({'x': 1}) 2

Parameters:

Returns:

Return type:

DeleteResult

Changed in version 4.1: Added let parameter. Added comment 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.

Added in version 3.0.

async delete_many(filter, collation=None, hint=None, session=None, let=None, comment=None)

Delete one or more documents matching the filter.

await db.test.count_documents({'x': 1}) 3 result = await db.test.delete_many({'x': 1}) result.deleted_count 3 await db.test.count_documents({'x': 1}) 0

Parameters:

Returns:

Return type:

DeleteResult

Changed in version 4.1: Added let parameter. Added comment 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.

Added in version 3.0.

async aggregate(pipeline, session=None, let=None, comment=None, **kwargs)

Perform an aggregation using the aggregation framework on this collection.

The aggregate() method obeys the read_preference of thisAsyncCollection, except when $out or $merge are used on MongoDB <5.0, in which casePRIMARY is used.

Note

The write_concern of this collection is automatically applied to this operation.

Parameters:

Return type:

AsyncCommandCursor[_DocumentType]

All optional aggregate command parameters should be passed as keyword arguments to this method. Valid options include, but are not limited to:

Returns:

A AsyncCommandCursor over the result set.

Parameters:

Return type:

AsyncCommandCursor[_DocumentType]

Changed in version 4.1: Added comment parameter. Added let parameter. Support mergeandmerge and mergeandout executing on secondaries according to the collection’s read_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 an AsyncCommandCursor. The pipeline argument must be a list.

async aggregate_raw_batches(pipeline, session=None, comment=None, **kwargs)

Perform an aggregation and retrieve batches of raw BSON.

Similar to the aggregate() method but returns aAsyncRawBatchCursor.

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’sbson module.

import bson cursor = await db.test.aggregate_raw_batches([ ... {'$project': {'x': {'$multiply': [2, '$x']}}}]) async 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.

Added in version 3.6.

Parameters:

Return type:

AsyncRawBatchCursor[_DocumentType]

async watch(pipeline=None, full_document=None, resume_after=None, max_await_time_ms=None, batch_size=None, collation=None, start_at_operation_time=None, session=None, start_after=None, comment=None, full_document_before_change=None, show_expanded_events=None)

Watch changes on this collection.

Performs an aggregation with an implicit initial $changeStreamstage and returns aAsyncCollectionChangeStream cursor which iterates over changes on this collection.

async with await db.collection.watch() as stream: async for change in stream: print(change)

The AsyncCollectionChangeStream 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: async with await db.coll.watch([{"$match": {"operationType": "insert"}}]) as stream: async for insert_change in stream: print(insert_change) except pymongo.errors.PyMongoError: # The AsyncChangeStream encountered an unrecoverable error or the # resume attempt failed to recreate the cursor. logging.error("...")

For a precise description of the resume process see thechange streams specification.

Note

Using this helper method is preferred to directly callingaggregate() with a$changeStream stage, for the purpose of supporting resumability.

Warning

This AsyncCollection’s read_concern must beReadConcern("majority") in order to use the $changeStreamstage.

Parameters:

Returns:

A AsyncCollectionChangeStream cursor.

Return type:

AsyncCollectionChangeStream[_DocumentType]

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.

Added in version 3.6.

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 ofAsyncCursor corresponding to this query.

The find() method obeys the read_preference of this AsyncCollection.

Parameters:

Return type:

AsyncCursor[__DocumentType_]

Note

There are a number of caveats to usingEXHAUST as cursor_type:

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 the oplog_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 the max_scan option. Support for this option is deprecated in MongoDB 4.0. Use max_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 the modifiers 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 to filter, projection, no_cursor_timeout, and allow_partial_results respectively. Added the cursor_type, oplog_replay, and modifiersoptions. Removed the network_timeout, read_preference, tag_sets,secondary_acceptable_latency_ms, max_scan, snapshot,tailable, await_data, exhaust, as_class, and slave_okay parameters. Removed compile_re option: PyMongo now always represents BSON regular expressions as Regexobjects. Use try_compile() to attempt to convert from a BSON regular expression to a Python regular expression object. Soft deprecated the manipulate 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 aAsyncRawBatchCursor.

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’sbson module.

import bson cursor = db.test.find_raw_batches() async 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.

Added in version 3.6.

Parameters:

Return type:

AsyncRawBatchCursor[__DocumentType_]

async 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, or None if no matching document is found.

The find_one() method obeys the read_preference of this AsyncCollection.

Parameters:

Return type:

_DocumentType | None

async find_one_and_delete(filter, projection=None, sort=None, hint=None, session=None, let=None, comment=None, **kwargs)

Finds a single document and deletes it, returning the document.

await db.test.count_documents({'x': 1}) 2 await db.test.find_one_and_delete({'x': 1}) {'x': 1, '_id': ObjectId('54f4e12bfba5220aa4d6dee8')} await db.test.count_documents({'x': 1}) 1

If multiple documents match filter, a sort can be applied.

async for doc in db.test.find({'x': 1}): ... print(doc) ... {'x': 1, '_id': 0} {'x': 1, '_id': 1} {'x': 1, '_id': 2} await 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.

await db.test.find_one_and_delete({'x': 1}, projection={'_id': False}) {'x': 1}

Parameters:

Return type:

_DocumentType

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 theWriteConcern of thisAsyncCollection 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.

Added in version 3.0.

async 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.

async for doc in db.test.find({}): ... print(doc) ... {'x': 1, '_id': 0} {'x': 1, '_id': 1} {'x': 1, '_id': 2} await db.test.find_one_and_replace({'x': 1}, {'y': 1}) {'x': 1, '_id': 0} async for doc in db.test.find({}): ... print(doc) ... {'y': 1, '_id': 0} {'x': 1, '_id': 1} {'x': 1, '_id': 2}

Parameters:

Return type:

_DocumentType

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 theWriteConcern of thisAsyncCollection 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.

Added in version 3.0.

async 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.

await 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.

await 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 await 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.

await 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.

(await db.example.delete_many({})).deleted_count 1 await 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.

async for doc in db.test.find({'done': True}): ... print(doc) ... {'_id': 665, 'done': True, 'result': {'count': 26}} {'_id': 701, 'done': True, 'result': {'count': 17}} await db.test.find_one_and_update( ... {'done': True}, ... {'$set': {'final': True}}, ... sort=[('_id', pymongo.DESCENDING)]) {'_id': 701, 'done': True, 'result': {'count': 17}}

Parameters:

Return type:

_DocumentType

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 and session 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 theWriteConcern of thisAsyncCollection 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.

Added in version 3.0.

async count_documents(filter, session=None, comment=None, **kwargs)

Count the number of documents in this collection.

Note

For a fast count of the total documents in a collection seeestimated_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:

The count_documents() method obeys the read_preference of this AsyncCollection.

Note

When migrating from count() to count_documents()the following query operators must be replaced:

Parameters:

Return type:

int

Added in version 3.7.

async estimated_document_count(comment=None, **kwargs)

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:

Parameters:

Return type:

int

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 theMongoDB Stable API. Users of the Stable API with estimated_document_count are recommended to upgrade their server version to 5.0.9+ or setpymongo.server_api.ServerApi.strict to False to avoid encountering errors.

Added in version 3.7.

async distinct(key, filter=None, session=None, comment=None, hint=None, **kwargs)

Get a list of distinct values for key among all documents in this collection.

Raises TypeError if key is not an instance ofstr.

All optional distinct parameters should be passed as keyword arguments to this method. Valid options include:

The distinct() method obeys the read_preference of this AsyncCollection.

Parameters:

Return type:

list

Changed in version 4.12: Added hint parameter.

Changed in version 3.6: Added session parameter.

Changed in version 3.4: Support the collation option.

async create_index(keys, session=None, comment=None, **kwargs)

Creates an index on this collection.

Takes either a single key or a list containing (key, direction) pairs or keys. If no direction is given, ASCENDING will be assumed. The key(s) must be an instance of str 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:

await my_collection.create_index("mike")

For a compound index on 'mike' descending and 'eliot'ascending we need to use a list of tuples:

await my_collection.create_index([("mike", pymongo.DESCENDING), ... "eliot"])

All optional index creation parameters should be passed as keyword arguments to this method. For example:

await my_collection.create_index([("mike", pymongo.DESCENDING)], ... background=True)

Valid options include, but are not limited to:

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:

Return type:

str

Changed in version 4.4: Allow passing a list containing (key, direction) pairs or keys for the keys parameter.

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.

async create_indexes(indexes, session=None, comment=None, **kwargs)

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)]) await db.test.create_indexes([index1, index2]) ["hello_world", "goodbye_-1"]

Parameters:

Return type:

list[str]

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.

Added in version 3.0.

async drop_index(index_or_name, session=None, comment=None, **kwargs)

Drops the specified index on this collection.

Can be used on non-existent collections or collections with no indexes. Raises OperationFailure on an error (e.g. trying to drop an index that does not exist). index_or_namecan 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 indexmust be dropped by name.

Parameters:

Return type:

None

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.

async drop_indexes(session=None, comment=None, **kwargs)

Drops all indexes on this collection.

Can be used on non-existent collections or collections with no indexes. Raises OperationFailure on an error.

Parameters:

Return type:

None

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.

async list_indexes(session=None, comment=None)

Get a cursor over the index documents for this collection.

async for index in await db.test.list_indexes(): ... print(index) ... SON([('v', 2), ('key', SON([('_id', 1)])), ('name', 'id')])

Parameters:

Returns:

An instance of AsyncCommandCursor.

Return type:

AsyncCommandCursor[MutableMapping[str, Any]]

Changed in version 4.1: Added comment parameter.

Changed in version 3.6: Added session parameter.

Added in version 3.0.

async index_information(session=None, comment=None)

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:

await db.test.create_index("x", unique=True) 'x_1' await db.test.index_information() {'id': {'key': [('_id', 1)]}, 'x_1': {'unique': True, 'key': [('x', 1)]}}

Parameters:

Return type:

MutableMapping[str, Any]

Changed in version 4.1: Added comment parameter.

Changed in version 3.6: Added session parameter.

async create_search_index(model, session=None, comment=None, **kwargs)

Create a single search index for the current collection.

Parameters:

Returns:

The name of the new search index.

Return type:

str

Note

requires a MongoDB server version 7.0+ Atlas cluster.

Added in version 4.5.

async create_search_indexes(models, session=None, comment=None, **kwargs)

Create multiple search indexes for the current collection.

Parameters:

Returns:

A list of the newly created search index names.

Return type:

list[str]

Note

requires a MongoDB server version 7.0+ Atlas cluster.

Added in version 4.5.

async drop_search_index(name, session=None, comment=None, **kwargs)

Delete a search index by index name.

Parameters:

Return type:

None

Note

requires a MongoDB server version 7.0+ Atlas cluster.

Added in version 4.5.

async list_search_indexes(name=None, session=None, comment=None, **kwargs)

Return a cursor over search indexes for the current collection.

Parameters:

Returns:

A AsyncCommandCursor over the result set.

Return type:

AsyncCommandCursor[Mapping[str, Any]]

Note

requires a MongoDB server version 7.0+ Atlas cluster.

Added in version 4.5.

async update_search_index(name, definition, session=None, comment=None, **kwargs)

Update a search index by replacing the existing index definition with the provided definition.

Parameters:

Return type:

None

Note

requires a MongoDB server version 7.0+ Atlas cluster.

Added in version 4.5.

async drop(session=None, comment=None, encrypted_fields=None)

Alias for drop_collection().

Parameters:

Return type:

None

The following two calls are equivalent:

await db.foo.drop() await 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 this AsyncCollection’s write_concern.

Changed in version 3.6: Added session parameter.

async rename(new_name, session=None, comment=None, **kwargs)

Rename this collection.

If operating in auth mode, client must be authorized as an admin to perform this operation. Raises TypeError ifnew_name is not an instance of str. Raises InvalidNameif new_name is not a valid collection name.

Parameters:

Return type:

MutableMapping[str, Any]

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.

async options(session=None, comment=None)

Get the options set on this collection.

Returns a dictionary of options and their values - seecreate_collection() for more information on the possible options. Returns an empty dictionary if the collection has not been created yet.

Parameters:

Return type:

MutableMapping[str, Any]

Changed in version 3.6: Added session parameter.

__getitem__(name)

Parameters:

name (str)

Return type:

AsyncCollection[__DocumentType_]

__getattr__(name)

Get a sub-collection of this collection by name.

Raises InvalidName if an invalid collection name is used.

Parameters:

name (str) – the name of the collection to get

Return type:

AsyncCollection[__DocumentType_]