For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.
Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
MongoDB Branding Shape
Click here >
Docs Menu

Configure CRUD Operations

In this guide, you can learn how to configure read and write operations in PyMongo.

You can control how the driver routes read operations by setting a read preference. You can also control options for how the driver waits for acknowledgment of read and write operations on a replica set by setting a read concern and a write concern.

By default, databases inherit these settings from the MongoClient instance, and collections inherit them from the database. However, you can change these settings on your database or collection by using one of the following methods:

  • get_database(): Gets the database and applies the client's read preference, read concern, and write preference.

  • database.with_options(): Gets the database and applies its current read preference, read concern, and write preference.

  • get_collection(): Gets the collection and applies its current read preference, read concern, and write preference.

  • collection.with_options(): Gets the collection and applies the database's read preference, read concern, and write preference.

To change read or write settings with the preceding methods, call the method and pass in the collection or database name, and the new read preference, read concern, or write preference.

The following example shows how to change the read preference, read concern and write preference of a database called test-database with the get_database() method:

client.get_database("test-database",
read_preference=ReadPreference.SECONDARY,
read_concern="local",
write_concern="majority")

The following example shows how to change read and write settings of a collection called test-collection with the get_collection() method:

database.get_collection("test-collection",
read_preference=ReadPreference.SECONDARY,
read_concern="local",
write_concern="majority")

The following example shows how to change read and write settings of a collection called test-collection with the with_options() method:

collection.with_options(read_preference=ReadPreference.SECONDARY,
read_concern="local",
write_concern="majority")

Tip

To see the types of read preferences available in the ReadPreference enum, see the API documentation.

To learn more about the read and write settings, see the following guides in the MongoDB Server manual:

In MongoDB Server, you can apply key-value tags to replica-set members according to any criteria you choose. You can then use those tags to target one or more members for a read operation.

By default, PyMongo ignores tags when choosing a member to read from. To instruct PyMongo to prefer certain tags, pass them as a parameter to your read preference class constructor.

In the following code example, the tag set passed to the read_preference parameter instructs PyMongo to prefer reads from the New York data center ('dc': 'ny') and to fall back to the San Francisco data center ('dc': 'sf'):

db = client.get_database(
'test', read_preference=Secondary([{'dc': 'ny'}, {'dc': 'sf'}]))

When connecting to a replica set with a non-primary read preference, the driver reads from the nearest eligible replica set member within the latency window. When connecting to a sharded cluster, the driver selects from all reachable mongos instances within the latency window. To learn about read preference modes, see Read Preference.

By default, the driver uses only those servers whose ping times are within 15 milliseconds of the nearest eligible server.

For example, suppose your replica set has five members and the nearest member has a ping time of 5 milliseconds. With the default localThresholdMS of 15 milliseconds, only members with a ping time of 20 milliseconds or less are within the latency window, as shown in the following table:

Host
Type
Ping Time
Within Latency Window

host1

Primary

5ms

Yes

host2

Secondary

9ms

Yes

host3

Secondary

13ms

Yes

host4

Secondary

24ms

No

host5

Secondary

42ms

No

To adjust the latency window, pass the localThresholdMS option to the MongoClient() constructor.

The following example specifies a local threshold of 35 milliseconds. Select the Synchronous or Asynchronous tab to see the corresponding code:

client = MongoClient(replicaSet='repl0',
readPreference=ReadPreference.SECONDARY_PREFERRED,
localThresholdMS=35)
client = AsyncMongoClient(replicaSet='repl0',
readPreference=ReadPreference.SECONDARY_PREFERRED,
localThresholdMS=35)

In the preceding example, PyMongo distributes reads between matching members within 35 milliseconds of the closest member's ping time.

Note

PyMongo ignores the value of localThresholdMS when communicating with a replica set through a mongos instance. In this case, use the localThreshold command-line option.

PyMongo automatically retries certain read and write operations a single time if they fail due to a network or server error.

You can explicitly disable retryable reads or retryable writes by setting the retryReads or retryWrites option to False in the MongoClient() constructor. The following example disables retryable reads and writes for a client. Select the Synchronous or Asynchronous tab to see the corresponding code:

client = MongoClient("<connection string>",
retryReads=False, retryWrites=False)
client = AsyncMongoClient("<connection string>",
retryReads=False, retryWrites=False)

To learn more about supported retryable read operations, see Retryable Reads in the MongoDB Server manual. To learn more about supported retryable write operations, see Retryable Writes in the MongoDB Server manual.

You can configure how PyMongo handles operations when a server returns an overload error by using the following client options:

  • enable_overload_retargeting: Specifies whether the driver deprioritizes a server that returns an overload error, reducing the likelihood of retrying on the same overloaded server. The default value is False.

  • max_adaptive_retries: Specifies the maximum number of times the driver retries an operation when a server returns an overload error. The default value is 2.

The following example creates a MongoClient and configures the overload retry options. Select the Synchronous or Asynchronous tab to see the corresponding code:

client = MongoClient("<connection string>",
enable_overload_retargeting=True,
max_adaptive_retries=3)
client = AsyncMongoClient("<connection string>",
enable_overload_retargeting=True,
max_adaptive_retries=3)

When you create a collection, you can specify a default collation for all operations you perform on the collection.

A collation is a set of language-specific rules for string comparison, such as for letter case and accent marks.

To specify a collation, create an instance of the Collation class or a Python dictionary. For a list of options to pass to the Collation constructor or include as keys in the dictionary, see Collation in the MongoDB Server manual.

Tip

Import Collation

To create an instance of the Collation class, you must import it from pymongo.collation.

The following example creates the same collection as the previous example, but with a default collation of fr_CA. Select the Synchronous or Asynchronous tab to see the corresponding code:

from pymongo.collation import Collation
database = client["test_database"]
database.create_collection("example_collection", collation=Collation(locale='fr_CA'))
from pymongo.collation import Collation
database = client["test_database"]
await database.create_collection("example_collection", collation=Collation(locale='fr_CA'))