Changelog - PyMongo 4.15.5 documentation (original) (raw)
Changes in Version 4.15.5 (2025/12/02)¶
Version 4.15.5 is a bug fix release.
- Fixed a bug that could cause
AutoReconnect("connection pool paused")errors when cursors fetched more documents from the database after SDAM heartbeat failures.
Issues Resolved¶
See the PyMongo 4.15.5 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.15.4 (2025/10/21)¶
Version 4.15.4 is a bug fix release.
- Relaxed the callback type of with_transaction() to allow the broader Awaitable type rather than only Coroutine objects.
- Added the missing Python 3.14 trove classifier to the package metadata.
Issues Resolved¶
See the PyMongo 4.15.4 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.15.3 (2025/10/07)¶
Version 4.15.3 is a bug fix release.
- Fixed a memory leak when raising bson.errors.InvalidDocument with C extensions.
- Fixed the return type of the distinct(),
distinct(), pymongo.asynchronous.cursor.AsyncCursor.distinct(), and pymongo.asynchronous.cursor.AsyncCursor.distinct() methods.
Issues Resolved¶
See the PyMongo 4.15.3 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.15.2 (2025/10/01)¶
Version 4.15.2 is a bug fix release.
- Add wheels for Python 3.14 and 3.14t that were missing from 4.15.0 release. Drop the 3.13t wheel.
Issues Resolved¶
See the PyMongo 4.15.2 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.15.1 (2025/09/16)¶
Version 4.15.1 is a bug fix release.
- Fixed a bug in
encrypt()andencrypt()that would cause aTypeErrorwhen usingpymongocrypt<1.16by passing an unsupportedtype_optsparameter even if Queryable Encryption text queries beta was not used. - Fixed a bug in
AsyncMongoClientthat caused aServerSelectionTimeoutErrorwhen used withuvicorn,FastAPI, oruvloop.
Issues Resolved¶
See the PyMongo 4.15.1 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.15.0 (2025/09/10)¶
PyMongo 4.15 brings a number of changes including:
- Added TextOpts,TEXTPREVIEW,PREFIXPREVIEW,SUFFIXPREVIEW,SUBSTRINGPREVIEW, as part of the experimental Queryable Encryption text queries beta.
pymongocrypt>=1.16is required for text query support. - Added bson.decimal128.DecimalEncoder andbson.decimal128.DecimalDecoderto support encoding and decoding of BSON Decimal128 values to decimal.Decimal values using the TypeRegistry API.
- Added support for Windows
arm64wheels.
Changes in Version 4.14.1 (2025/08/19)¶
Version 4.14.1 is a bug fix release.
- Fixed a bug in
MongoClient.append_metadata()andAsyncMongoClient.append_metadata()that allowed duplicateDriverInfo.nameto be appended to the metadata.
Issues Resolved¶
See the PyMongo 4.14.1 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.14.0 (2025/08/06)¶
Warning
PyMongo 4.14 drops support for MongoDB 4.0. PyMongo now supports MongoDB 4.2+.
PyMongo 4.14 brings a number of changes including:
- Dropped support for MongoDB 4.0.
- Added preliminary support for Python 3.14 and 3.14 with free-threading. We do not yet support the following with Python 3.14:
- Subinterpreters (
concurrent.interpreters) - Free-threading with Encryption
- mod_wsgi
- Subinterpreters (
- Removed experimental support for free-threading support in Python 3.13.
- Added bson.codec_options.TypeRegistry.codecs andbson.codec_options.TypeRegistry.fallback_encoder properties to allow users to directly access the type codecs and fallback encoder for a given bson.codec_options.TypeRegistry.
- Added
pymongo.asynchronous.mongo_client.AsyncMongoClient.append_metadata()andpymongo.mongo_client.MongoClient.append_metadata()to allow instantiated MongoClients to send client metadata on-demand - Improved performance of selecting a server with the Primary selector.
- Introduces a minor breaking change. When encodingbson.binary.BinaryVector, a
ValueErrorwill be raised if the ‘padding’ metadata field is < 0 or > 7, or non-zero for any type other than PACKED_BIT. - Changed parse_uri()’s
optionsreturn value to be typedictinstead of_CaseInsensitiveDictionary.
Issues Resolved¶
See the PyMongo 4.14 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.13.2 (2025/06/17)¶
Version 4.13.2 is a bug fix release.
- Fixed a bug where
AsyncMongoClientwould block the event loop while creating new connections, potentially significantly increasing latency for ongoing operations.
Issues Resolved¶
See the PyMongo 4.13.2 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.13.1 (2025/06/10)¶
Version 4.13.1 is a bug fix release.
- Fixed a bug that could raise
ServerSelectionTimeoutErrorwhen using timeouts withAsyncMongoClient. - Fixed a bug that could raise
NetworkTimeouterrors on Windows.
Issues Resolved¶
See the PyMongo 4.13.1 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.13.0 (2025/05/14)¶
PyMongo 4.13 brings a number of changes including:
- The asynchronous API is now stable and no longer in beta. See the pymongo.asynchronous docs or the migration guide for more information.
- Fixed a bug where pymongo.write_concern.WriteConcern repr was not eval-able when using
w="majority". - When padding is set, ignored bits in a BSON BinaryVector of PACKED_BIT dtype should be set to zero. When encoding, this is enforced and is a breaking change. It is not yet enforced when decoding, so reading from the database will not fail, however a warning will be triggered. From PyMongo 5.0, this rule will be enforced for both encoding and decoding.
Issues Resolved¶
See the PyMongo 4.13 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.12.1 (2025/04/29)¶
Version 4.12.1 is a bug fix release.
- Fixed a bug that could raise
UnboundLocalErrorwhen creating asynchronous connections over SSL. - Fixed a bug causing SRV hostname validation to fail when resolver and resolved hostnames are identical with three domain levels.
- Fixed a bug that caused direct use of
pymongo.uri_parserto raise anAttributeError. - Fixed a bug where clients created with connect=False and a “mongodb+srv://” connection string could cause public
pymongo.MongoClientandpymongo.AsyncMongoClientattributes (topology_description, nodes, address, primary, secondaries, arbiters) to incorrectly return a Database, leading to type errors such as: “NotImplementedError: Database objects do not implement truth value testing or bool()”. - Removed Eventlet testing against Python versions newer than 3.9 since Eventlet is actively being sunset by its maintainers and has compatibility issues with PyMongo’s dnspython dependency.
- Fixed a bug where MongoDB cluster topology changes could cause asynchronous operations to take much longer to complete due to holding the Topology lock while closing stale connections.
- Fixed a bug that would cause AsyncMongoClient to attempt to use PyOpenSSL when available, resulting in errors such as “pymongo.errors.ServerSelectionTimeoutError: ‘SSLContext’ object has no attribute ‘wrap_bio’”.
Issues Resolved¶
See the PyMongo 4.12.1 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.12.0 (2025/04/08)¶
Warning
Driver support for MongoDB 4.0 reached end of life in April 2025. PyMongo 4.12 will be the last release to support MongoDB 4.0.
PyMongo 4.12 brings a number of changes including:
- Support for configuring DEK cache lifetime via the
key_expiration_msargument toAutoEncryptionOpts. - Support for $lookup in CSFLE and QE supported on MongoDB 8.1+.
- pymongocrypt>=1.13 is now required for In-Use Encryption support.
- Added
gridfs.asynchronous.grid_file.AsyncGridFSBucket.rename_by_name()andgridfs.grid_file.GridFSBucket.rename_by_name()for more performant renaming of a file with multiple revisions. - Added
gridfs.asynchronous.grid_file.AsyncGridFSBucket.delete_by_name()andgridfs.grid_file.GridFSBucket.delete_by_name()for more performant deletion of a file with multiple revisions. - AsyncMongoClient no longer performs DNS resolution for “mongodb+srv://” connection strings on creation. To avoid blocking the asyncio loop, the resolution is now deferred until the client is first connected.
- Added index hinting support to thedistinct() anddistinct() commands.
- Deprecated the
hedgeparameter forPrimaryPreferred,Secondary,SecondaryPreferred,Nearest. Support forhedgewill be removed in PyMongo 5.0. - Removed PyOpenSSL support from the asynchronous API due to limitations of the CPython asyncio.Protocol SSL implementation.
- Allow valid SRV hostnames with less than 3 parts.
Issues Resolved¶
See the PyMongo 4.12 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.11.2 (2025/03/05)¶
Version 4.11.2 is a bug fix release.
- Fixed a bug where command() would fail when attempting to run the bulkWrite command.
Issues Resolved¶
See the PyMongo 4.11.2 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.11.1 (2025/02/10)¶
- Fixed support for prebuilt
ppc64leands390xwheels.
Changes in Version 4.11.0 (2025/01/28)¶
Warning
PyMongo 4.11 drops support for Python 3.8 and PyPy 3.9: Python 3.9+ or PyPy 3.10+ is now required.
Warning
PyMongo 4.11 drops support for MongoDB 3.6. PyMongo now supports MongoDB 4.0+. Driver support for MongoDB 3.6 reached end of life in April 2024.
Warning
Driver support for MongoDB 4.0 reaches end of life in April 2025. A future minor release of PyMongo will raise the minimum supported MongoDB Server version from 4.0 to 4.2. This is in accordance with [MongoDB Software Lifecycle Schedules](https://www.mongodb.com/legal/support-policy/lifecycles).Support for MongoDB Server 4.0 will be dropped in a future release!
Warning
This version does not include wheels for ppc64le or s390x architectures, see PYTHON-5058 for more information.
PyMongo 4.11 brings a number of changes including:
- Dropped support for Python 3.8 and PyPy 3.9.
- Dropped support for MongoDB 3.6.
- Dropped support for the MONGODB-CR authenticate mechanism, which is no longer supported by MongoDB 4.0+.
- pymongocrypt>=1.12 is now required for In-Use Encryption support.
- Added support for free-threaded Python with the GIL disabled. For more information see:Free-threaded CPython. We do not yet support free-threaded Python on Windows (PYTHON-5027) or with In-Use Encryption (PYTHON-5024).
- address andaddress now correctly block when called on unconnected clients until either connection succeeds or a server selection timeout error is raised.
- Added repr() support to pymongo.operations.IndexModel.
- Added repr() support to pymongo.operations.SearchIndexModel.
- Added
sortparameter toupdate_one(), replace_one(),UpdateOne, andUpdateMany, - bulk_write() andbulk_write() now throw an error when
ordered=TrueorverboseResults=Trueare used with unacknowledged writes. These are unavoidable breaking changes. - Fixed a bug in bson.json_util.dumps where a bson.datetime_ms.DatetimeMS would be incorrectly encoded as
'{"$date": "X"}'instead of'{"$date": X}'when using the legacy MongoDB Extended JSON datetime representation. - Fixed a bug where bson.json_util.loads would raise an IndexError when parsing an invalid
"$date"instead of a ValueError.
Issues Resolved¶
See the PyMongo 4.11 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.10.1 (2024/10/01)¶
Version 4.10.1 is a bug fix release.
- Fixed a bug where did_upsert() would raise a
TypeError. - Fixed Binary BSON subtype (9) support on big-endian operating systems (such as zSeries).
Issues Resolved¶
See the PyMongo 4.10.1 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.10.0 (2024/09/30)¶
- Added provisional (BETA) support for a new Binary BSON subtype (9) used for efficient storage and retrieval of vectors: densely packed arrays of numbers, all of the same type. This includes new methods from_vector() and as_vector().
- Added C extension use to client metadata, for example:
{"driver": {"name": "PyMongo|c", "version": "4.10.0"}, ...} - Fixed a bug where AsyncMongoClient could deadlock.
- Fixed a bug where PyMongo could fail to import on Windows if
asynciois misconfigured.
Issues Resolved¶
See the PyMongo 4.10 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.9.2 (2024/10/02)¶
- Fixed a bug where AsyncMongoClient could deadlock.
- Fixed a bug where PyMongo could fail to import on Windows if
asynciois misconfigured. - Fixed a bug where did_upsert() would raise a
TypeError.
Issues Resolved¶
See the PyMongo 4.9.2 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.9.1 (2024/09/18)¶
- Add missing documentation about the fact the async API is in beta state.
Issues Resolved¶
See the PyMongo 4.9.1 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.9 (2024/09/18)¶
Warning
Driver support for MongoDB 3.6 reached end of life in April 2024. PyMongo 4.9 will be the last release to support MongoDB 3.6.
Warning
PyMongo 4.9 refactors a large portion of internal APIs to support the new asynchronous API beta. As a result, versions of Motor older than 3.6 are not compatible with PyMongo 4.9. Existing users of these versions must either upgrade to Motor 3.6 and PyMongo 4.9, or cap their PyMongo version to < 4.9. Any applications that use private APIs may also break as a result of these internal changes.
PyMongo 4.9 brings a number of improvements including:
- Added support for MongoDB 8.0.
- Added support for Python 3.13.
- A new beta asynchronous API with full asyncio support. This new asynchronous API is a work-in-progress that may change during the beta period before the full release.
- Added support for In-Use Encryption range queries with MongoDB 8.0. Added RANGE.
sparsityandtrim_factorare now optional in RangeOpts. - Added support for the “delegated” option for the KMIP
master_keyincreate_data_key(). - pymongocrypt>=1.10 is now required for In-Use Encryption support.
- Added to_list() to Cursor,CommandCursor,AsyncCursor, and AsyncCommandCursoras an asynchronous-friendly alternative to
list(cursor). - Added bulk_write() to MongoClientand AsyncMongoClient, enabling users to perform insert, update, and delete operations against mixed namespaces in a minimized number of round trips. Please see Client Bulk Write for more information.
- Added support for the
namespaceparameter to theInsertOne,ReplaceOne,UpdateOne,UpdateMany,DeleteOne, andDeleteMany operations, so they can be used in the new bulk_write(). - Added repr() support to bson.tz_util.FixedOffset.
- Fixed a bug where PyMongo would raise
InvalidBSON: unhashable type: 'tzfile'when using DATETIME_CLAMP orDATETIME_AUTO with a timezone from dateutil. - Fixed a bug where PyMongo would raise
InvalidBSON: date value out of rangewhen using DATETIME_CLAMP orDATETIME_AUTO with a non-UTC timezone. - Added a warning to unclosed MongoClient instances telling users to explicitly close clients when finished with them to avoid leaking resources. For example:
sys:1: ResourceWarning: Unclosed MongoClient opened at:
File "/Users//my_file.py", line 8, in ``
client = MongoClient()
Call MongoClient.close() to safely shut down your client and free up resources.
- The default value for
connectinMongoClientis changed toFalsewhen running on unction-as-a-service (FaaS) like AWS Lambda, Google Cloud Functions, and Microsoft Azure Functions. On some FaaS systems, there is afork()operation at function startup. By delaying the connection to the first operation, we avoid a deadlock. Seemultiple forks for more information.
Issues Resolved¶
See the PyMongo 4.9 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.8.0 (2024/06/26)¶
Warning
PyMongo 4.8 drops support for Python 3.7 and PyPy 3.8: Python 3.8+ or PyPy 3.9+ is now required.
PyMongo 4.8 brings a number of improvements including:
- The handshake metadata for “os.name” on Windows has been simplified to “Windows” to improve import time.
- The repr of
bson.binary.Binaryis now redacted when the subtype is SENSITIVE_SUBTYPE(8). - Secure Software Development Life Cycle automation for release process. GitHub Releases now include a Software Bill of Materials, and signature files corresponding to the distribution files released on PyPI.
- Fixed a bug in change streams where both
startAtOperationTimeandresumeTokencould be added to a retry attempt, which caused the retry to fail. - Fallback to stdlib
sslmodule whenpyopensslimport fails with AttributeError. - Improved performance of MongoClient operations, especially when many operations are being run concurrently.
Unavoidable breaking changes¶
- Since we are now using
hatchas our build backend, we no longer have a usablesetup.pyfile and require installation usingpip. Attempts to invoke thesetup.pyfile will raise an exception. Additionally,pip>= 21.3 is now required for editable installs. - We no longer support the
srvextra, sincednspythonis included as a dependency in PyMongo 4.7+. Instead ofpip install pymongo[srv], usepip install pymongo. - We no longer support the
tlsextra, which was only valid for Python 2. Instead ofpip install pymongo[tls], usepip install pymongo.
Issues Resolved¶
See the PyMongo 4.8 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.7.3 (2024/06/04)¶
Version 4.7.3 has further fixes for lazily loading modules.
- Use deferred imports instead of importlib lazy module loading.
- Improve import time on Windows.
- Reduce verbosity of “Waiting for suitable server to become available” log message from info to debug.
Issues Resolved¶
See the PyMongo 4.7.3 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.7.2 (2024/05/07)¶
Version 4.7.2 fixes a bug introduced in 4.7.0:
- Fixed a bug where PyMongo could not be used with the Nuitka compiler.
Issues Resolved¶
See the PyMongo 4.7.2 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.7.1 (2024/04/30)¶
Version 4.7.1 fixes a bug introduced in 4.7.0:
- Fixed a bug where PyMongo would cause an
AttributeErrorifdns.resolverwas imported and referenced after PyMongo was imported. - Clarified the behavior of the
TOKEN_RESOURCEauth mechanism property forMONGODB-OIDC.
Issues Resolved¶
See the PyMongo 4.7.1 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.7.0 (2024/04/24)¶
PyMongo 4.7 brings a number of improvements including:
- Added support for
MONGODB-OIDCauthentication. The MONGODB-OIDC mechanism authenticates using an OpenID Connect (OIDC) access token. The driver supports OIDC for workload identity, defined as an identity you assign to a software workload (such as an application, service, script, or container) to authenticate and access other services and resources. Please see Authentication for more information. - Added support for Python’s native logging library, enabling developers to customize the verbosity of log messages for their applications. Please see Logging for more information.
- Significantly improved the performance of encoding BSON documents to JSON.
- Added support for named KMS providers for client side field level encryption. Previously supported KMS providers were only: aws, azure, gcp, kmip, and local. The KMS provider is now expanded to support name suffixes (e.g. local:myname). Named KMS providers enables more than one of each KMS provider type to be configured. See the docstring for AutoEncryptionOpts. Note that named KMS providers requires pymongocrypt >=1.9 and libmongocrypt >=1.9.
- Added the
pymongo.hello.Hello.connection_id,pymongo.monitoring.CommandStartedEvent.server_connection_id,pymongo.monitoring.CommandSucceededEvent.server_connection_id, andpymongo.monitoring.CommandFailedEvent.server_connection_id properties. - Fixed a bug where inflating a RawBSONDocument containing a Code would cause an error.
- encrypt() andencrypt_expression() now allow
key_idto be passed in as a uuid.UUID. - Fixed a bug where Int64 instances could not always be encoded by orjson. The following now works:
import orjson
from bson import json_util
orjson.dumps({'a': Int64(1)}, default=json_util.default, option=orjson.OPT_PASSTHROUGH_SUBCLASS) - Fixed a bug appearing in Python 3.12 where “RuntimeError: can’t create new thread at interpreter shutdown” could be written to stderr when a MongoClient’s thread starts as the python interpreter is shutting down.
- Added a warning when connecting to DocumentDB and CosmosDB clusters. For more information regarding feature compatibility and support please visitmongodb.com/supportability/documentdb andmongodb.com/supportability/cosmosdb.
- Added the pymongo.monitoring.ConnectionCheckedOutEvent.duration,pymongo.monitoring.ConnectionCheckOutFailedEvent.duration, andpymongo.monitoring.ConnectionReadyEvent.duration properties.
- Added the
typeandkwargsarguments to SearchIndexModel to enable creating vector search indexes in MongoDB Atlas. - Fixed a bug where
read_concernandwrite_concernwere improperly added tolist_search_indexes() queries. - Deprecated
pymongo.write_concern.WriteConcern.wtimeoutandpymongo.mongo_client.MongoClient.wTimeoutMS. Use timeout() instead.
Warning
PyMongo depends on dnspython, which released version 2.6.1 with a fix forCVE-2023-29483. We do not explicitly require that version, but we strongly recommend that you install at least that version in your environment.
Unavoidable breaking changes¶
- Replaced usage of bson.son.SON on all internal classes and commands to dict,
options.pool_options.metadatais now of typedictas opposed to bson.son.SON. Here’s some examples of how this changes expected output as well as how to convert from dict to bson.son.SON:
Before
from pymongo import MongoClient
client = MongoClient()
client.options.pool_options.metadata
SON([('driver', SON([('name', 'PyMongo'), ('version', '4.7.0.dev0')])), ('os', SON([('type', 'Darwin'), ('name', 'Darwin'), ('architecture', 'arm64'), ('version', '14.3')])), ('platform', 'CPython 3.11.6.final.0')])
After
client.options.pool_options.metadata
{'driver': {'name': 'PyMongo', 'version': '4.7.0.dev0'}, 'os': {'type': 'Darwin', 'name': 'Darwin', 'architecture': 'arm64', 'version': '14.3'}, 'platform': 'CPython 3.11.6.final.0'}
To convert from dict to SON
This will only convert the first layer of the dictionary
data_as_dict = client.options.pool_options.metadata
SON(data_as_dict)
SON([('driver', {'name': 'PyMongo', 'version': '4.7.0.dev0'}), ('os', {'type': 'Darwin', 'name': 'Darwin', 'architecture': 'arm64', 'version': '14.3'}), ('platform', 'CPython 3.11.6.final.0')])
To convert from dict to SON on a nested dictionary
def dict_to_SON(data_as_dict: dict[Any, Any]):
... data_as_SON = SON()
... for key, value in data_as_dict.items():
... data_as_SON[key] = dict_to_SON(value) if isinstance(value, dict) else value
... return data_as_SONdict_to_SON(data_as_dict)
SON([('driver', SON([('name', 'PyMongo'), ('version', '4.7.0.dev0')])), ('os', SON([('type', 'Darwin'), ('name', 'Darwin'), ('architecture', 'arm64'), ('version', '14.3')])), ('platform', 'CPython 3.11.6.final.0')])
- PyMongo now uses lazy imports for external dependencies. If you are relying on any kind of monkey-patching of the standard library, you may need to explicitly import those external libraries in addition to
pymongobefore applying the patch. Note that we test withgeventandeventletpatching, and those continue to work. - The “aws” extra now requires minimum version of
1.1.0forpymongo_auth_aws.
Changes in Version 4.6.3 (2024/03/27)¶
PyMongo 4.6.3 fixes the following bug:
- Fixed a potential memory access violation when decoding invalid bson.
Issues Resolved¶
See the PyMongo 4.6.3 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.6.2 (2024/02/21)¶
PyMongo 4.6.2 fixes the following bug:
- Fixed a bug appearing in Python 3.12 where “RuntimeError: can’t create new thread at interpreter shutdown” could be written to stderr when a MongoClient’s thread starts as the python interpreter is shutting down.
Issues Resolved¶
See the PyMongo 4.6.2 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.6.1 (2023/11/29)¶
PyMongo 4.6.1 fixes the following bug:
- Ensure retryable read
OperationFailureerrors re-raise exception when 0 or NoneType error code is provided.
Issues Resolved¶
See the PyMongo 4.6.1 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.6.0 (2023/11/01)¶
PyMongo 4.6 brings a number of improvements including:
- Added the
serverMonitoringModeURI and keyword argument to MongoClient. - Improved client performance and reduced connection requirements in Function-as-a-service (FaaS) environments like AWS Lambda, Google Cloud Functions, and Microsoft Azure Functions.
- Added the pymongo.monitoring.CommandSucceededEvent.database_name property.
- Added the pymongo.monitoring.CommandFailedEvent.database_name property.
- Allow passing a
dictto sort/create_index/hint. - Added repr() support to the write result classes:BulkWriteResult,DeleteResult,InsertManyResult,InsertOneResult,UpdateResult, andRewrapManyDataKeyResult. For example:
client.t.t.insert_one({})
InsertOneResult(ObjectId('65319acdd55bb3a27ab5502b'), acknowledged=True)
client.t.t.insert_many([{} for _ in range(3)])
InsertManyResult([ObjectId('6532f85e826f2b6125d6ce39'), ObjectId('6532f85e826f2b6125d6ce3a'), ObjectId('6532f85e826f2b6125d6ce3b')], acknowledged=True) - parse_uri() now considers the delimiting slash (
/) between hosts and connection options optional. For example, “mongodb://example.com?tls=true” is now a valid URI. - Fixed a bug where PyMongo would incorrectly promote all cursors to exhaust cursors when connected to load balanced MongoDB clusters or Serverless clusters.
- Added the network compression documentation page.
- Added more timeout information to network errors.
Issues Resolved¶
See the PyMongo 4.6 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.5.0 (2023/08/22)¶
PyMongo 4.5 brings a number of improvements including:
- Added new helper methods for Atlas Search Index (requires MongoDB Server 7.0+):list_search_indexes(),create_search_index(),create_search_indexes(),drop_search_index(),update_search_index()
- Added cursor_command()and try_next() to support executing an arbitrary command that returns a cursor.
cryptography2.5 or later is now required for OCSP support.- Improved bson encoding and decoding performance by up to 134%(PYTHON-3729, PYTHON-3797, PYTHON-3816, PYTHON-3817, PYTHON-3820, PYTHON-3824, and PYTHON-3846).
Warning
PyMongo no longer supports PyPy3 versions older than 3.8. Users must upgrade to PyPy3.8+.
Issues Resolved¶
See the PyMongo 4.5 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.4.1 (2023/07/13)¶
Version 4.4.1 fixes the following bugs:
- Fixed a bug where pymongo would raise a
ConfigurationError: Invalid SRV hosterror when connecting to a “mongodb+srv://” URI that included capital letters in the SRV hosts returned from DNS. (PYTHON-3800). - Fixed a minor reference counting bug in the C extension (PYTHON-3798).
Issues Resolved¶
See the PyMongo 4.4.1 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.4.0 (2023/06/21)¶
PyMongo 4.4 brings a number of improvements including:
- Added support for MongoDB 7.0.
- Added support for Python 3.11.
- Added support for passing a list containing (key, direction) pairs or keys to create_index().
- Improved bson encoding performance (PYTHON-3717 and PYTHON-3718).
- Improved support for Pyright to improve typing support for IDEs like Visual Studio Code or Visual Studio.
- Improved support for type-checking with MyPy “strict” mode (–strict).
- Added create_encrypted_collection(),EncryptedCollectionError,encrypt_expression(),RangeOpts, and RANGEPREVIEW as part of the experimental Queryable Encryption beta.
- pymongocrypt 1.6.0 or later is now required for In-Use Encryption support. MongoDB Server 7.0 introduced a backwards breaking change to the QE protocol. Users taking advantage of the Queryable Encryption beta must now upgrade to MongoDB 7.0+ and PyMongo 4.4+.
- Previously, PyMongo’s docs recommended using datetime.datetime.utcnow() anddatetime.datetime.utcfromtimestamp(). utcnow and utcfromtimestamp are deprecated in Python 3.12, for reasons explained in this Github issue. Instead, users should use
datetime.datetime.now(tz=timezone.utc)()anddatetime.datetime.fromtimestamp(tz=timezone.utc)()instead.
Issues Resolved¶
See the PyMongo 4.4 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.3.3 (2022/11/17)¶
Version 4.3.3 documents support for the following:
- CSFLE on-demand credentials for cloud KMS providers.
- Authentication support for EKS Clusters.
- Added the timeout example page to improve the documentation for pymongo.timeout().
Bug Fixes¶
- Fixed a performance regression in download_to_stream()and download_to_stream_by_name() by reading in chunks instead of line by line (PYTHON-3502).
- Improved performance of gridfs.grid_file.GridOut.read() and
gridfs.grid_file.GridOut.readline()(PYTHON-3508).
Issues Resolved¶
See the PyMongo 4.3.3 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.3.2 (2022/10/18)¶
Note: We withheld uploading tags 4.3.0 and 4.3.1 to PyPI due to a version handling error and a necessary documentation update.
dnspython is now a required dependency. This change makes PyMongo easier to install for use with “mongodb+srv://” connection strings and MongoDB Atlas.
PyMongo 4.3 brings a number of improvements including:
- Added support for decoding BSON datetimes outside of the range supported by Python’s datetime builtin. Seehandling out of range datetimes for examples, as well asbson.datetime_ms.DatetimeMS,bson.codec_options.DatetimeConversion, andbson.codec_options.CodecOptions’s
datetime_conversionparameter for more details (PYTHON-1824). - PyMongo now resets its locks and other shared state in the child process after a os.fork() to reduce the frequency of deadlocks. Note that deadlocks are still possible because libraries that PyMongo depends like OpenSSL cannot be made fork() safe in multithreaded applications. (PYTHON-2484). For more info see multiple forks.
- When used with MongoDB 6.0+, ChangeStream s now allow for new types of events (such as DDL and C2C replication events) to be recorded with the new parameter
show_expanded_eventsthat can be passed to methods such as watch(). - PyMongo now internally caches AWS credentials that it fetches from AWS endpoints, to avoid rate limitations. The cache is cleared when the credentials expire or an error is encountered.
- When using the
MONGODB-AWSauthentication mechanism with theawsextra, the behavior of credential fetching has changed withpymongo_auth_aws>=1.1.0. Please see Authentication for more information.
Bug fixes¶
- Fixed a bug where ChangeStreamwould allow an app to retry calling
next()ortry_next()even after non-resumable errors (PYTHON-3389). - Fixed a bug where the client could be unable to discover the new primary after a simultaneous replica set election and reconfig (PYTHON-2970).
Issues Resolved¶
See the PyMongo 4.3 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.2.0 (2022/07/20)¶
Warning
PyMongo 4.2 drops support for Python 3.6: Python 3.7+ is now required.
PyMongo 4.2 brings a number of improvements including:
- Support for MongoDB 6.0.
- Support for the Queryable Encryption beta with MongoDB 6.0. Note that backwards-breaking changes may be made before the final release. See automatic queryable client-side encryption for example usage.
- Provisional (beta) support for pymongo.timeout() to apply a single timeout to an entire block of pymongo operations. See timeout for examples.
- Added the
timeoutMSURI and keyword argument to MongoClient. - Added the pymongo.errors.PyMongoError.timeout property which is
Truewhen the error was caused by a timeout. - Added the
check_existsargument to create_collection()that when True (the default) runs an additionallistCollectionscommand to verify that the collection does not exist already. - Added the following key management APIs to ClientEncryption:
- Support for the
crypt_sharedlibrary to replacemongocryptdusing the newcrypt_shared_lib_pathandcrypt_shared_lib_requiredarguments toAutoEncryptionOpts.
Bug fixes¶
- Fixed a bug where estimated_document_count()would fail with a “CommandNotSupportedOnView” error on views (PYTHON-2885).
- Fixed a bug where invalid UTF-8 strings could be passed as patterns for Regexobjects. bson.encode() now correctly raises bson.errors.InvalidStringData (PYTHON-3048).
- Fixed a bug that caused
AutoReconnect("connection pool paused")errors in the child process after fork (PYTHON-3257). - Fixed a bug where count_documents() anddistinct() would fail in a transaction with
directConnection=True(PYTHON-3333). - GridFS no longer uploads an incomplete files collection document after encountering an error in the middle of an upload fork. This results in fewerCorruptGridFile errors (PYTHON-1552).
- Renamed PyMongo’s internal C extension methods to avoid crashing due to name conflicts with mpi4py and other shared libraries (PYTHON-2110).
- Fixed tight CPU loop for network I/O when using PyOpenSSL (PYTHON-3187).
Unavoidable breaking changes¶
- pymongocrypt 1.3.0 or later is now required for client side field level encryption support.
- estimated_document_count() 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 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.strictto
Falseto avoid encountering errors (PYTHON-3167). - Removed generic typing from ClientSession to improve support for Pyright (PYTHON-3283).
- Added
__all__to the bson, pymongo, and gridfs packages. This could be a breaking change for apps that relied onfrom bson import *to import APIs not present in__all__(PYTHON-3311).
Issues Resolved¶
See the PyMongo 4.2 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.1.1 (2022/04/13)¶
Version 4.1.1 fixes a number of bugs:
- Fixed a memory leak bug when calling decode_all() without a
codec_optionsargument (PYTHON-3222). - Fixed a bug where decode_all() did not accept
codec_optionsas a keyword argument (PYTHON-3222). - Fixed an oversight where type markers (py.typed files) were not included in our release distributions (PYTHON-3214).
- Fixed a bug where pymongo would raise a “NameError: name sys is not defined” exception when attempting to parse a “mongodb+srv://” URI when the dnspython dependency was not installed (PYTHON-3198).
Issues Resolved¶
See the PyMongo 4.1.1 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.1 (2021/12/07)¶
Warning
PyMongo 4.1 drops support for Python 3.6.0 and 3.6.1, Python 3.6.2+ is now required.
PyMongo 4.1 brings a number of improvements including:
- Type Hinting support (formerly provided by pymongo-stubs). See Type Hints for more information.
- Added support for the
commentparameter to all helpers. For example seeinsert_one(). - Added support for the
letparameter toupdate_one(),update_many(),delete_one(),delete_many(),replace_one(),aggregate(),find_one_and_delete(),find_one_and_replace(),find_one_and_update(),find(),find_one(), and bulk_write().letis a map of parameter names and values. Parameters can then be accessed as variables in an aggregate expression context. - aggregate() now supports mergeandmerge and mergeandout executing on secondaries on MongoDB >=5.0. aggregate() now always obeys the collection’s
read_preferenceon MongoDB >= 5.0. - gridfs.grid_file.GridOut.seek() now returns the new position in the file, to conform to the behavior of io.IOBase.seek().
- Improved reuse of implicit sessions (PYTHON-2956).
Bug fixes¶
- Fixed bug that would cause SDAM heartbeat timeouts and connection churn on AWS Lambda and other FaaS environments (PYTHON-3186).
- Fixed bug where MongoClient,Database, and Collectionmistakenly implemented typing.Iterable (PYTHON-3084).
Issues Resolved¶
See the PyMongo 4.1 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 4.0.2 (2022/03/03)¶
- No changes
Changes in Version 4.0.1 (2021/12/07)¶
- No changes
Changes in Version 4.0 (2021/11/29)¶
Warning
PyMongo 4.0 drops support for Python 2.7, 3.4, and 3.5.
Warning
PyMongo 4.0 drops support for MongoDB 2.6, 3.0, 3.2, and 3.4.
Warning
PyMongo 4.0 changes the default value of the directConnection URI option and keyword argument to MongoClientto False instead of None, allowing for the automatic discovery of replica sets. This means that if you want a direct connection to a single server you must passdirectConnection=True as a URI option or keyword argument. For more details, see the relevant section of the PyMongo 4.x migration guide: directConnection defaults to False.
PyMongo 4.0 brings a number of improvements as well as some backward breaking changes. For example, all APIs deprecated in PyMongo 3.X have been removed. Be sure to read the changes listed below and the PyMongo 4 Migration Guidebefore upgrading from PyMongo 3.x.
Breaking Changes in 4.0¶
- Removed support for Python 2.7, 3.4, and 3.5. Python 3.6.2+ is now required.
- The default uuid_representation for CodecOptions,JSONOptions, andMongoClient has been changed frombson.binary.UuidRepresentation.PYTHON_LEGACY tobson.binary.UuidRepresentation.UNSPECIFIED. Attempting to encode auuid.UUID instance to BSON or JSON now produces an error by default. See UUID representations for details.
- Removed the
waitQueueMultiplekeyword argument toMongoClient and removedpymongo.errors.ExceededMaxWaiters. - Removed the
socketKeepAlivekeyword argument toMongoClient. - Removed
pymongo.mongo_client.MongoClient.fsync(),pymongo.mongo_client.MongoClient.unlock(), andpymongo.mongo_client.MongoClient.is_locked. - Removed
pymongo.mongo_client.MongoClient.database_names(). - Removed
pymongo.mongo_client.MongoClient.max_bson_size. - Removed
pymongo.mongo_client.MongoClient.max_message_size. - Removed
pymongo.mongo_client.MongoClient.max_write_batch_size. - Removed
pymongo.mongo_client.MongoClient.event_listeners. - Removed
pymongo.mongo_client.MongoClient.max_pool_size. - Removed
pymongo.mongo_client.MongoClient.max_idle_time_ms. - Removed
pymongo.mongo_client.MongoClient.local_threshold_ms. - Removed
pymongo.mongo_client.MongoClient.server_selection_timeout. - Removed
pymongo.mongo_client.MongoClient.retry_writes. - Removed
pymongo.mongo_client.MongoClient.retry_reads. - Removed
pymongo.database.Database.eval(),pymongo.database.Database.system_jsandpymongo.database.SystemJS. - Removed
pymongo.database.Database.collection_names(). - Removed
pymongo.database.Database.current_op(). - Removed
pymongo.database.Database.authenticate()andpymongo.database.Database.logout(). - Removed
pymongo.database.Database.error(),pymongo.database.Database.last_status(),pymongo.database.Database.previous_error(),pymongo.database.Database.reset_error_history(). - Removed
pymongo.database.Database.add_user()andpymongo.database.Database.remove_user(). - Removed support for database profiler helpers
profiling_level(),set_profiling_level(), andprofiling_info(). Instead, users should run the profile command with thecommand() helper directly. - Removed
pymongo.OFF,pymongo.SLOW_ONLY, andpymongo.ALL. - Removed
pymongo.collection.Collection.parallel_scan(). - Removed
pymongo.collection.Collection.ensure_index(). - Removed
pymongo.collection.Collection.reindex(). - Removed
pymongo.collection.Collection.save(). - Removed
pymongo.collection.Collection.insert(). - Removed
pymongo.collection.Collection.update(). - Removed
pymongo.collection.Collection.remove(). - Removed
pymongo.collection.Collection.find_and_modify(). - Removed
pymongo.collection.Collection.count(). - Removed
pymongo.collection.Collection.initialize_ordered_bulk_op(),pymongo.collection.Collection.initialize_unordered_bulk_op(), andpymongo.bulk.BulkOperationBuilder. Usepymongo.collection.Collection.bulk_write() instead. - Removed
pymongo.collection.Collection.group(). - Removed
pymongo.collection.Collection.map_reduce()andpymongo.collection.Collection.inline_map_reduce(). - Removed the
useCursoroption foraggregate(). - Removed
pymongo.mongo_client.MongoClient.close_cursor(). Usepymongo.cursor.Cursor.close() instead. - Removed
pymongo.mongo_client.MongoClient.kill_cursors(). - Removed
pymongo.cursor_manager.CursorManagerandpymongo.cursor_manager. - Removed
pymongo.mongo_client.MongoClient.set_cursor_manager(). - Removed
pymongo.cursor.Cursor.count(). - Removed
pymongo.thread_util. - Removed
MongoReplicaSetClient. - Removed
IsMaster. UseHelloinstead. - Removed
pymongo.son_manipulator,pymongo.son_manipulator.SONManipulator,pymongo.son_manipulator.ObjectIdInjector,pymongo.son_manipulator.ObjectIdShuffler,pymongo.son_manipulator.AutoReference,pymongo.son_manipulator.NamespaceInjector,pymongo.database.Database.add_son_manipulator(),pymongo.database.Database.outgoing_copying_manipulators,pymongo.database.Database.outgoing_manipulators,pymongo.database.Database.incoming_copying_manipulators, andpymongo.database.Database.incoming_manipulators. - Removed the
manipulateandmodifiersparameters fromfind(),find_one(),find_raw_batches(), andCursor(). - Removed
pymongo.message.delete(),pymongo.message.get_more(),pymongo.message.insert(),pymongo.message.kill_cursors(),pymongo.message.query(), andpymongo.message.update(). - Removed
pymongo.errors.NotMasterError. Use pymongo.errors.NotPrimaryError instead. - Removed
pymongo.errors.CertificateError. - Removed
pymongo.GEOHAYSTACK. - Removed
bson.binary.UUIDLegacy. - Removed
bson.json_util.STRICT_JSON_OPTIONS. UseRELAXED_JSON_OPTIONS orCANONICAL_JSON_OPTIONS instead. - Changed the default JSON encoding representation from legacy to relaxed. The json_mode parameter for bson.json_util.dumps now defaults toRELAXED_JSON_OPTIONS.
- Changed the BSON and JSON decoding behavior of DBRefto match the behavior outlined in the DBRef specification version 1.0. Specifically, PyMongo now only decodes a subdocument into aDBRef if and only if, it contains both
$refand$idfields and the$ref,$id, and$dbfields are of the correct type. Otherwise the document is returned as normal. Previously, any subdocument containing a$reffield would be decoded as aDBRef. - The “tls” install extra is no longer necessary or supported and will be ignored by pip.
- The
tz_awareargument to JSONOptionsnow defaults toFalseinstead ofTrue. bson.json_util.loads() now decodes datetime as naive by default. See tz_aware defaults to False for more info. directConnectionURI option and keyword argument to MongoClientdefaults toFalseinstead ofNone, allowing for the automatic discovery of replica sets. This means that if you want a direct connection to a single server you must passdirectConnection=Trueas a URI option or keyword argument.- The
hintoption is now required when usingminormaxqueries with find(). nameis now a required argument for the pymongo.driver_info.DriverInfo class.- When providing a “mongodb+srv://” URI toMongoClient constructor you can now use the
srvServiceNameURI option to specify your own SRV service name. items()now returns adict_itemsobject rather than a list.- Removed
bson.son.SON.iteritems(). - Collection and Databasenow raises an error upon evaluating as a Boolean, please use the syntax
if collection is not None:orif database is not None:as opposed to the previous syntax which was simplyif collection:orif database:. You must now explicitly compare with None. - MongoClient cannot execute any operations after being closed. The previous behavior would simply reconnect. However, now you must create a new instance.
- Classes Int64, MinKey,MaxKey, Timestamp,Regex, and DBRef all implement
__slots__now. This means that their attributes are fixed, and new attributes cannot be added to them at runtime. - Empty projections (eg {} or []) forfind(), andfind_one()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. - MongoClient now raises aConfigurationError when more than one URI is passed into the
hostsargument. MongoClient`now raises anInvalidURI exception when it encounters unescaped percent signs in username and password when parsing MongoDB URIs.- Comparing two MongoClient instances now uses a set of immutable properties rather thanaddress which can change.
- Removed the
disable_md5parameter for GridFSBucket andGridFS. See disable_md5 parameter is removed for details. - pymongocrypt 1.2.0 or later is now required for client side field level encryption support.
Notable improvements¶
- Enhanced connection pooling to create connections more efficiently and avoid connection storms.
- Added the
maxConnectingURI andMongoClient keyword argument. - MongoClient now accepts a URI and keyword argument
srvMaxHoststhat limits the number of mongos-like hosts a client will connect to. More specifically, when a mongodb+srv:// connection string resolves to more thansrvMaxHostsnumber of hosts, the client will randomly choose asrvMaxHostssized subset of hosts. - Added pymongo.mongo_client.MongoClient.options for read-only access to a client’s configuration options.
- Support for the “kmip” KMS provider for client side field level encryption. See the docstring for AutoEncryptionOptsand encryption.
Issues Resolved¶
See the PyMongo 4.0 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 3.13.0 (2022/11/01)¶
Version 3.13 provides an upgrade path to PyMongo 4.x. Most of the API changes from PyMongo 4.0 have been backported in a backward compatible way, allowing applications to be written against PyMongo >= 3.13, rather then PyMongo 3.x or PyMongo 4.x. See the PyMongo 4 Migration Guide for detailed examples.
Notable improvements¶
- Added pymongo.mongo_client.MongoClient.options for read-only access to a client’s configuration options.
Issues Resolved¶
PyMongo 3.13 drops support for Python 3.4.
Bug fixes¶
- Fixed a memory leak bug when calling decode_all() without a
codec_optionsargument (PYTHON-3222). - Fixed a bug where decode_all() did not accept
codec_optionsas a keyword argument (PYTHON-3222).
Deprecations¶
- Deprecated
map_reduce()andinline_map_reduce(). Use aggregate() instead. - Deprecated
pymongo.mongo_client.MongoClient.event_listeners. Useevent_listenersinstead. - Deprecated
pymongo.mongo_client.MongoClient.max_pool_size. Usemax_pool_sizeinstead. - Deprecated
pymongo.mongo_client.MongoClient.max_idle_time_ms. Usemax_idle_time_secondsinstead. - Deprecated
pymongo.mongo_client.MongoClient.local_threshold_ms. Uselocal_threshold_msinstead. - Deprecated
pymongo.mongo_client.MongoClient.server_selection_timeout. Useserver_selection_timeoutinstead. - Deprecated
pymongo.mongo_client.MongoClient.retry_writes. Useretry_writesinstead. - Deprecated
pymongo.mongo_client.MongoClient.retry_reads. Useretry_readsinstead. - Deprecated
pymongo.mongo_client.MongoClient.max_bson_size,pymongo.mongo_client.MongoClient.max_message_size, andpymongo.mongo_client.MongoClient.max_write_batch_size. These helpers were incorrect when inloadBalanced=true modeand ambiguous in clusters with mixed versions. Use the hello command to get the authoritative value from the remote server instead. Code like this:
max_bson_size = client.max_bson_size
max_message_size = client.max_message_size
max_write_batch_size = client.max_write_batch_size
can be changed to this:
doc = client.admin.command('hello') max_bson_size = doc['maxBsonObjectSize'] max_message_size = doc['maxMessageSizeBytes'] max_write_batch_size = doc['maxWriteBatchSize']
See the PyMongo 3.13.0 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 3.12.3 (2021/12/07)¶
Issues Resolved¶
Version 3.12.3 fixes a bug that prevented bson.json_util.loads() from decoding a document with a non-string “$regex” field (PYTHON-3028).
See the PyMongo 3.12.3 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 3.12.2 (2021/11/29)¶
Issues Resolved¶
Version 3.12.2 fixes a number of bugs:
- Fixed a bug that prevented PyMongo from retrying bulk writes after a
writeConcernErroron MongoDB 4.4+ (PYTHON-2984). - Fixed a bug that could cause the driver to hang during automatic client side field level encryption (PYTHON-3017).
See the PyMongo 3.12.2 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 3.12.1 (2021/10/19)¶
Issues Resolved¶
Version 3.12.1 fixes a number of bugs:
- Fixed a bug that caused a multi-document transaction to fail when the first operation was large bulk write (>48MB) that required splitting a batched write command (PYTHON-2915).
- Fixed a bug that caused the
tlsDisableOCSPEndpointCheckURI option to be applied incorrectly (PYTHON-2866).
See the PyMongo 3.12.1 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 3.12.0 (2021/07/13)¶
Warning
PyMongo 3.12.0 deprecates support for Python 2.7, 3.4 and 3.5. These Python versions will not be supported by PyMongo 4.
Warning
PyMongo now allows insertion of documents with keys that include dots (‘.’) or start with dollar signs (‘$’).
- pymongocrypt 1.1.0 or later is now required for client side field level encryption support.
- Iterating over gridfs.grid_file.GridOut now moves through the file line by line instead of chunk by chunk, and does not restart at the top for subsequent iterations on the same object. Call
seek(0)to reset the iterator.
Notable improvements¶
- Added support for MongoDB 5.0.
- Support for MongoDB Stable API, see ServerApi.
- Support for snapshot reads on secondaries (see snapshot reads).
- Support for Azure and GCP KMS providers for client side field level encryption. See the docstring for MongoClient,AutoEncryptionOpts, and encryption.
- Support AWS authentication with temporary credentials when connecting to KMS in client side field level encryption.
- Support for connecting to load balanced MongoDB clusters via the new
loadBalancedURI option. - Support for creating timeseries collections via the
timeseriesandexpireAfterSecondsarguments tocreate_collection(). - Added pymongo.mongo_client.MongoClient.topology_description.
- Added hash support to MongoClient,Database andCollection (PYTHON-2466).
- Improved the error message returned byinsert_many() when supplied with an argument of incorrect type (PYTHON-1690).
- Added session and read concern support tofind_raw_batches()and aggregate_raw_batches().
Bug fixes¶
- Fixed a bug that could cause the driver to deadlock during automatic client side field level encryption (PYTHON-2472).
- Fixed a potential deadlock when garbage collecting an unclosed exhaustCursor.
- Fixed an bug where using gevent.Timeout to timeout an operation could lead to a deadlock.
- Fixed the following bug with Atlas Data Lake. When closing cursors, pymongo now sends killCursors with the namespace returned the cursor’s initial command response.
- Fixed a bug in RawBatchCursor that caused it to return an empty bytestring when the cursor contained no results. It now raises StopIteration instead.
Deprecations¶
- Deprecated support for Python 2.7, 3.4 and 3.5.
- Deprecated support for database profiler helpers
profiling_level(),set_profiling_level(), andprofiling_info(). Instead, users should run the profile command with thecommand() helper directly. - Deprecated
NotMasterError. Users should use NotPrimaryError instead. - Deprecated
IsMasterandismasterwhich will be removed in PyMongo 4.0 and are replaced byHelloandhellowhich provide the same API. - Deprecated the
pymongo.messeagemodule. - Deprecated the
ssl_keyfileandssl_certfileURI options in favor oftlsCertificateKeyFile(see TLS).
Issues Resolved¶
See the PyMongo 3.12.0 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 3.11.3 (2021/02/02)¶
Issues Resolved¶
Version 3.11.3 fixes a bug that prevented PyMongo from retrying writes after a writeConcernError on MongoDB 4.4+ (PYTHON-2452)
See the PyMongo 3.11.3 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 3.11.2 (2020/12/02)¶
Issues Resolved¶
Version 3.11.2 includes a number of bugfixes. Highlights include:
- Fixed a memory leak caused by failing SDAM monitor checks on Python 3 (PYTHON-2433).
- Fixed a regression that changed the string representation ofBulkWriteError (PYTHON-2438).
- Fixed a bug that made it impossible to usebson.codec_options.CodecOptions.with_options() andwith_options() on some early versions of Python 3.4 and Python 3.5 due to a bug in the standard library implementation of
collections.namedtuple._asdict()(PYTHON-2440). - Fixed a bug that resulted in a TypeError exception when a PyOpenSSL socket was configured with a timeout of
None(PYTHON-2443).
See the PyMongo 3.11.2 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 3.11.1 (2020/11/17)¶
Version 3.11.1 adds support for Python 3.9 and includes a number of bugfixes. Highlights include:
- Support for Python 3.9.
- Initial support for Azure and GCP KMS providers for client side field level encryption is in beta. See the docstring forMongoClient,AutoEncryptionOpts, and encryption. Note: Backwards-breaking changes may be made before the final release.
- Fixed a bug where the bson.json_util.JSONOptions API did not match the bson.codec_options.CodecOptions API due to the absence of a bson.json_util.JSONOptions.with_options() method. This method has now been added.
- Fixed a bug which made it impossible to serializeBulkWriteError instances using pickle.
- Fixed a bug wherein PyMongo did not always discard an implicit session after encountering a network error.
- Fixed a bug where connections created in the background were not authenticated.
- Fixed a memory leak in the bson module when using aTypeRegistry.
Issues Resolved¶
See the PyMongo 3.11.1 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 3.11.0 (2020/07/30)¶
Version 3.11 adds support for MongoDB 4.4 and includes a number of bug fixes. Highlights include:
- Support for OCSP (Online Certificate Status Protocol).
- Support for PyOpenSSL as an alternative TLS implementation. PyOpenSSL is required for OCSPsupport. It will also be installed when using the “tls” extra if the version of Python in use is older than 2.7.9.
- Support for the MONGODB-AWS authentication mechanism.
- Support for the
directConnectionURI option and kwarg toMongoClient. - Support for speculative authentication attempts in connection handshakes which reduces the number of network roundtrips needed to authenticate new connections on MongoDB 4.4+.
- Support for creating collections in multi-document transactions withcreate_collection() on MongoDB 4.4+.
- Added index hinting support to thereplace_one(),update_one(),update_many(),find_one_and_replace(),find_one_and_update(),delete_one(),delete_many(), andfind_one_and_delete() commands.
- Added index hinting support to theReplaceOne,UpdateOne,UpdateMany,DeleteOne, andDeleteMany bulk operations.
- Added support for bson.binary.UuidRepresentation.UNSPECIFIED and
MongoClient(uuidRepresentation='unspecified')which will become the default UUID representation starting in PyMongo 4.0. SeeUUID representations for details. - New methods bson.binary.Binary.from_uuid() andbson.binary.Binary.as_uuid().
- Added the
backgroundparameter topymongo.database.Database.validate_collection(). For a description of this parameter see the MongoDB documentation for the validate command. - Added the
allow_disk_useparameters topymongo.collection.Collection.find(). - Added the
hedgeparameter toPrimaryPreferred,Secondary,SecondaryPreferred,Nearest to support disabling (or explicitly enabling) hedged reads in MongoDB 4.4+. - Fixed a bug in change streams that could cause PyMongo to miss some change documents when resuming a stream that was started without a resume token and whose first batch did not contain any change documents.
- Fixed an bug where using gevent.Timeout to timeout an operation could lead to a deadlock.
Deprecations:
- Deprecated the
oplog_replayparameter topymongo.collection.Collection.find(). Starting in MongoDB 4.4, the server optimizes queries against the oplog collection without requiring the user to set this flag. - Deprecated
pymongo.collection.Collection.reindex(). Usecommand() to run thereIndexcommand instead. - Deprecated
pymongo.mongo_client.MongoClient.fsync(). Usecommand() to run thefsynccommand instead. - Deprecated
pymongo.mongo_client.MongoClient.unlock(). Usecommand() to run thefsyncUnlockcommand instead. See the documentation for more information. - Deprecated
pymongo.mongo_client.MongoClient.is_locked. Usecommand() to run thecurrentOpcommand instead. See the documentation for more information. - Deprecated
bson.binary.UUIDLegacy. Usebson.binary.Binary.from_uuid() instead.
Unavoidable breaking changes:
- GridFSBucket and GridFS do not support multi-document transactions. Running a GridFS operation in a transaction now always raises the following error:
InvalidOperation: GridFS does not support multi-document transactions
Issues Resolved¶
See the PyMongo 3.11.0 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 3.10.1 (2020/01/07)¶
Version 3.10.1 fixes the following issues discovered since the release of 3.10.0:
- Fix a TypeError logged to stderr that could be triggered during server maintenance or during pymongo.mongo_client.MongoClient.close().
- Avoid creating new connections duringpymongo.mongo_client.MongoClient.close().
Issues Resolved¶
See the PyMongo 3.10.1 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 3.10.0 (2019/12/10)¶
Version 3.10 includes a number of improvements and bug fixes. Highlights include:
- Support for Client-Side Field Level Encryption with MongoDB 4.2. SeeClient-Side Field Level Encryption for examples.
- Support for Python 3.8.
- Added pymongo.client_session.ClientSession.in_transaction.
- Do not hold the Topology lock while creating connections in a MongoClient’s background thread. This change fixes a bug where application operations would block while the background thread ensures that all server pools have minPoolSize connections.
- Fix a UnicodeDecodeError bug when coercing a PyMongoError with a non-ascii error message to unicode on Python 2.
- Fix an edge case bug where PyMongo could exceed the server’s maxMessageSizeBytes when generating a compressed bulk write command.
Issues Resolved¶
See the PyMongo 3.10 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 3.9.0 (2019/08/13)¶
Version 3.9 adds support for MongoDB 4.2. Highlights include:
- Support for MongoDB 4.2 sharded transactions. Sharded transactions have the same API as replica set transactions. See Transactions.
- New method pymongo.client_session.ClientSession.with_transaction() to support conveniently running a transaction in a session with automatic retries and at-most-once semantics.
- Initial support for client side field level encryption. See the docstring forMongoClient,AutoEncryptionOpts, and encryption for details. Note: Support for client side encryption is in beta. Backwards-breaking changes may be made before the final release.
- Added the
max_commit_time_msparameter tostart_transaction(). - Implement the URI options specification in theMongoClient() constructor. Consequently, there are a number of changes in connection options:
- The
tlsInsecureoption has been added. - The
tlsoption has been added. The olderssloption has been retained as an alias to the newtlsoption. wTimeouthas been deprecated in favor ofwTimeoutMS.wTimeoutMSnow overrideswTimeoutif the user provides both.jhas been deprecated in favor ofjournal.journalnow overridesjif the user provides both.ssl_cert_reqshas been deprecated in favor oftlsAllowInvalidCertificates. Instead ofssl.CERT_NONE,ssl.CERT_OPTIONALandssl.CERT_REQUIRED, the new option expects a boolean value -Trueis equivalent tossl.CERT_NONE, whileFalseis equivalent tossl.CERT_REQUIRED.ssl_match_hostnamehas been deprecated in favor oftlsAllowInvalidHostnames.ssl_ca_certshas been deprecated in favor oftlsCAFile.ssl_certfilehas been deprecated in favor oftlsCertificateKeyFile.ssl_pem_passphrasehas been deprecated in favor oftlsCertificateKeyFilePassword.waitQueueMultiplehas been deprecated without replacement. This option was a poor solution for putting an upper bound on queuing since it didn’t affect queuing in other parts of the driver.
- The
- The
retryWritesURI option now defaults toTrue. Supported write operations that fail with a retryable error will automatically be retried one time, with at-most-once semantics. - Support for retryable reads and the
retryReadsURI option which is enabled by default. See the MongoClientdocumentation for details. Now that supported operations are retried automatically and transparently, users should consider adjusting any custom retry logic to prevent an application from inadvertently retrying for too long. - Support zstandard for wire protocol compression.
- Support for periodically polling DNS SRV records to update the mongos proxy list without having to change client configuration.
- New method pymongo.database.Database.aggregate() to support running database level aggregations.
- Support for publishing Connection Monitoring and Pooling events via the newConnectionPoolListener class. Seemonitoring for an example.
- pymongo.collection.Collection.aggregate() andpymongo.database.Database.aggregate() now support the
$mergepipeline stage and use read preferencePRIMARY if the$outor$mergepipeline stages are used. - Support for specifying a pipeline or document inupdate_one(),update_many(),find_one_and_update(),UpdateOne(), andUpdateMany().
- New BSON utility functions encode() and decode()
- Binary now supports any bytes-like type that implements the buffer protocol.
- Resume tokens can now be accessed from a
ChangeStreamcursor using theresume_token attribute. - Connections now survive primary step-down when using MongoDB 4.2+. Applications should expect less socket connection turnover during replica set elections.
Unavoidable breaking changes:
- Applications that use MongoDB with the MMAPv1 storage engine must now explicitly disable retryable writes via the connection string (e.g.
MongoClient("mongodb://my.mongodb.cluster/db?retryWrites=false")) or the MongoClient constructor’s keyword argument (e.g.MongoClient("mongodb://my.mongodb.cluster/db", retryWrites=False)) to avoid running into OperationFailure exceptions during write operations. The MMAPv1 storage engine is deprecated and does not support retryable writes which are now turned on by default. - In order to ensure that the
connectTimeoutMSURI option is honored when connecting to clusters with amongodb+srv://connection string, the minimum required version of the optionaldnspythondependency has been bumped to 1.16.0. This is a breaking change for applications that use PyMongo’s SRV support with a version ofdnspythonolder than 1.16.0.
Issues Resolved¶
See the PyMongo 3.9 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 3.8.0 (2019/04/22)¶
Warning
PyMongo no longer supports Python 2.6. RHEL 6 users should install Python 2.7 or newer from Red Hat Software Collections. CentOS 6 users should install Python 2.7 or newer from SCL
Warning
PyMongo no longer supports PyPy3 versions older than 3.5. Users must upgrade to PyPy3.5+.
- ObjectId now implements the ObjectID specification version 0.2.
- For better performance and to better follow the GridFS spec,GridOut now uses a single cursor to read all the chunks in the file. Previously, each chunk in the file was queried individually using find_one().
- gridfs.grid_file.GridOut.read() now only checks for extra chunks after reading the entire file. Previously, this method would check for extra chunks on every call.
current_op()now always uses theDatabase’s codec_optionswhen decoding the command response. Previously the codec_options was only used when the MongoDB server version was <= 3.0.- Undeprecated get_default_database()and added the
defaultparameter. - TLS Renegotiation is now disabled when possible.
- Custom types can now be directly encoded to, and decoded from MongoDB using the TypeCodec andTypeRegistry APIs. For more information, seeCustom Types.
- Attempting a multi-document transaction on a sharded cluster now raises aConfigurationError.
- pymongo.cursor.Cursor.distinct() and
pymongo.cursor.Cursor.count()now send the Cursor’scomment() as the “comment” top-level command option instead of “$comment”. Also, note that “comment” must be a string. - Add the
filterparameter tolist_collection_names(). - Changes can now be requested from a
ChangeStreamcursor without blocking indefinitely using the newpymongo.change_stream.ChangeStream.try_next() method. - Fixed a reference leak bug when splitting a batched write command based on maxWriteBatchSize or the max message size.
- Deprecated running find queries that set min()and/or max() but do not also set ahint() of which index to use. The find command is expected to require a hint() when using min/max starting in MongoDB 4.2.
- Documented support for the uuidRepresentation URI option, which has been supported since PyMongo 2.7. Valid values are
pythonLegacy(the default),javaLegacy,csharpLegacyandstandard. New applications should consider setting this tostandardfor cross language compatibility. - RawBSONDocument now validates that the
bson_bytespassed in represent a single bson document. Earlier versions would mistakenly accept multiple bson documents. - Iterating over a RawBSONDocument now maintains the same field order of the underlying raw BSON document.
- Applications can now register a custom server selector. For more information see Customize Server Selection.
- The connection pool now implements a LIFO policy.
Unavoidable breaking changes:
- In order to follow the ObjectID Spec version 0.2, an ObjectId’s 3-byte machine identifier and 2-byte process id have been replaced with a single 5-byte random value generated per process. This is a breaking change for any application that attempts to interpret those bytes.
Issues Resolved¶
See the PyMongo 3.8 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 3.7.2 (2018/10/10)¶
Version 3.7.2 fixes a few issues discovered since the release of 3.7.1.
- Fixed a bug in retryable writes where a previous command’s “txnNumber” field could be sent leading to incorrect results.
- Fixed a memory leak of a few bytes on some insert, update, or delete commands when running against MongoDB 3.6+.
- Fixed a bug that caused
pymongo.collection.Collection.ensure_index()to only cache a single index per database. - Updated the documentation examples to usepymongo.collection.Collection.count_documents() instead of
pymongo.collection.Collection.count()andpymongo.cursor.Cursor.count().
Issues Resolved¶
See the PyMongo 3.7.2 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 3.7.1 (2018/07/16)¶
Version 3.7.1 fixes a few issues discovered since the release of 3.7.0.
- Calling
authenticate()more than once with the same credentials results in OperationFailure. - Authentication fails when SCRAM-SHA-1 is used to authenticate users with only MONGODB-CR credentials.
- A millisecond rounding problem when decoding datetimes in the pure Python BSON decoder on 32 bit systems and AWS lambda.
Issues Resolved¶
See the PyMongo 3.7.1 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 3.7.0 (2018/06/26)¶
Version 3.7 adds support for MongoDB 4.0. Highlights include:
- Support for single replica set multi-document ACID transactions. See transactions.
- Support for wire protocol compression via the new
compressorsURI and keyword argument toMongoClient(). See network compression for details. - Support for Python 3.7.
- New count methods, count_documents()and estimated_document_count().count_documents() is always accurate when used with MongoDB 3.6+, or when used with older standalone or replica set deployments. With older sharded clusters is it always accurate when used with Primary read preference. It can also be used in a transaction, unlike the now deprecated
pymongo.collection.Collection.count()andpymongo.cursor.Cursor.count()methods. - Support for watching changes on all collections in a database using the new pymongo.database.Database.watch() method.
- Support for watching changes on all collections in all databases using the new pymongo.mongo_client.MongoClient.watch() method.
- Support for watching changes starting at a user provided timestamp using the new
start_at_operation_timeparameter for thewatch()helpers. - Better support for using PyMongo in a FIPS 140-2 environment. Specifically, the following features and changes allow PyMongo to function when MD5 support is disabled in OpenSSL by the FIPS Object Module:
- Support for the SCRAM-SHA-256authentication mechanism. The GSSAPI,PLAIN, and MONGODB-X509mechanisms can also be used to avoid issues with OpenSSL in FIPS environments.
- MD5 checksums are now optional in GridFS. See the
disable_md5option of GridFS and GridFSBucket. - ObjectId machine bytes are now hashed usingFNV-1ainstead of MD5.
- The list_collection_names() and
collection_names()methods use the nameOnly option when supported by MongoDB. - The pymongo.collection.Collection.watch() method now returns an instance of the CollectionChangeStreamclass which is a subclass of ChangeStream.
- SCRAM client and server keys are cached for improved performance, followingRFC 5802.
- If not specified, the authSource for the PLAINauthentication mechanism defaults to $external.
- wtimeoutMS is once again supported as a URI option.
- When using unacknowledged write concern and connected to MongoDB server version 3.6 or greater, the
bypass_document_validationoption is now supported in the following write helpers:insert_one(),replace_one(),update_one(),update_many().
Deprecations:
- Deprecated
pymongo.collection.Collection.count()andpymongo.cursor.Cursor.count(). These two methods use thecountcommand and may or may not be accurate, depending on the options used and connected MongoDB topology. Usecount_documents() instead. - Deprecated the snapshot option of find()and find_one(). The option was deprecated in MongoDB 3.6 and removed in MongoDB 4.0.
- Deprecated the max_scan option of find()and find_one(). The option was deprecated in MongoDB 4.0. Use
maxTimeMSinstead. - Deprecated
close_cursor(). Useclose() instead. - Deprecated
database_names(). Uselist_database_names() instead. - Deprecated
collection_names(). Uselist_collection_names() instead. - Deprecated
parallel_scan(). MongoDB 4.2 will remove the parallelCollectionScan command.
Unavoidable breaking changes:
- Commands that fail with server error codes 10107, 13435, 13436, 11600, 11602, 189, 91 (NotMaster, NotMasterNoSlaveOk, NotMasterOrSecondary, InterruptedAtShutdown, InterruptedDueToReplStateChange, PrimarySteppedDown, ShutdownInProgress respectively) now always raise
NotMasterErrorinstead ofOperationFailure. parallel_scan()no longer uses an implicit session. Explicit sessions are still supported.- Unacknowledged writes (
w=0) with an explicitsessionparameter now raise a client side error. Since PyMongo does not wait for a response for an unacknowledged write, two unacknowledged writes run serially by the client may be executed simultaneously on the server. However, the server requires a single session must not be used simultaneously by more than one operation. Therefore explicit sessions cannot support unacknowledged writes. Unacknowledged writes without asessionparameter are still supported.
Issues Resolved¶
See the PyMongo 3.7 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 3.6.1 (2018/03/01)¶
Version 3.6.1 fixes bugs reported since the release of 3.6.0:
- Fix regression in PyMongo 3.5.0 that causes idle sockets to be closed almost instantly when
maxIdleTimeMSis set. Idle sockets are now closed aftermaxIdleTimeMSmilliseconds. pymongo.mongo_client.MongoClient.max_idle_time_msnow returns milliseconds instead of seconds.- Properly import and use themonotoniclibrary for monotonic time when it is installed.
- aggregate() now ignores the
batchSizeargument when running a pipeline with a$outstage. - Always send handshake metadata for new connections.
Issues Resolved¶
See the PyMongo 3.6.1 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 3.6.0 (2017/08/23)¶
Version 3.6 adds support for MongoDB 3.6, drops support for CPython 3.3 (PyPy3 is still supported), and drops support for MongoDB versions older than 2.6. If connecting to a MongoDB 2.4 server or older, PyMongo now throws aConfigurationError.
Highlights include:
- Support for change streams. See thewatch() method for details.
- Support for array_filters inupdate_one(),update_many(),find_one_and_update(),UpdateOne(), andUpdateMany().
- New Session API, see start_session().
- New methods find_raw_batches() andaggregate_raw_batches() for use with external libraries that can parse raw batches of BSON data.
- New methods list_databases() andlist_database_names().
- New methods list_collections() andlist_collection_names().
- Support for mongodb+srv:// URIs. SeeMongoClient for details.
- Index management helpers (create_index(),create_indexes(),drop_index(),drop_indexes(),
reindex()) now support maxTimeMS. - Support for retryable writes and the
retryWritesURI option. SeeMongoClient for details.
Deprecations:
- The
useCursoroption for aggregate()is deprecated. The option was only necessary when upgrading from MongoDB 2.4 to MongoDB 2.6. MongoDB 2.4 is no longer supported. - The
add_user()andremove_user()methods are deprecated. See the method docstrings for alternatives.
Unavoidable breaking changes:
- Starting in MongoDB 3.6, the deprecated methods
authenticate()andlogout()now invalidate all cursors created prior. Instead of using these methods to change credentials, pass credentials for one user to the MongoClient at construction time, and either grant access to several databases to one user account, or use a distinct client object for each user. - BSON binary subtype 4 is decoded using RFC-4122 byte order regardless of the UUID representation. This is a change in behavior for applications that use UUID representation bson.binary.JAVA_LEGACY orbson.binary.CSHARP_LEGACY to decode BSON binary subtype 4. Other UUID representations, bson.binary.PYTHON_LEGACY (the default) andbson.binary.STANDARD, and the decoding of BSON binary subtype 3 are unchanged.
Issues Resolved¶
See the PyMongo 3.6 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 3.5.1 (2017/08/23)¶
Version 3.5.1 fixes bugs reported since the release of 3.5.0:
- Work around socket.getsockopt issue with NetBSD.
- pymongo.command_cursor.CommandCursor.close() now closes the cursor synchronously instead of deferring to a background thread.
- Fix documentation build warnings with Sphinx 1.6.x.
Issues Resolved¶
See the PyMongo 3.5.1 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 3.5.0 (2017/08/08)¶
Version 3.5 implements a number of improvements and bug fixes:
Highlights include:
- Username and password can be passed toMongoClient as keyword arguments. Before, the only way to pass them was in the URI.
- Increased the performance of using RawBSONDocument.
- Increased the performance of
database_names()by using thenameOnlyoption for listDatabases when available. - Increased the performance ofbulk_write() by reducing the memory overhead of InsertOne,DeleteOne, andDeleteMany.
- Added the
collationoption to DeleteOne,DeleteMany,ReplaceOne,UpdateOne, andUpdateMany. - Implemented the MongoDB Extended JSONspecification.
- Decimal128 now works when cdecimal is installed.
- PyMongo is now tested against a wider array of operating systems and CPU architectures (including s390x, ARM64, and POWER8).
Changes and Deprecations:
- find() has new options
return_key,show_record_id,snapshot,hint,max_time_ms,max_scan,min,max, andcomment. Deprecated the optionmodifiers. - Deprecated
group(). The group command was deprecated in MongoDB 3.4 and is expected to be removed in MongoDB 3.6. Applications should use aggregate()with the$grouppipeline stage instead. - Deprecated
authenticate(). Authenticating multiple users conflicts with support for logical sessions in MongoDB 3.6. To authenticate as multiple users, create multiple instances ofMongoClient. - Deprecated
eval(). The eval command was deprecated in MongoDB 3.0 and will be removed in a future server version. - Deprecated
SystemJS. - Deprecated get_default_database(). Applications should useget_database() without the
`name`parameter instead. - Deprecated the MongoClient option
socketKeepAlive`. It now defaults to true and disabling it is not recommended, see does TCP keepalive time affect MongoDB Deployments? - Deprecated
initialize_ordered_bulk_op(),initialize_unordered_bulk_op(), andBulkOperationBuilder. Usebulk_write() instead. - Deprecated
STRICT_JSON_OPTIONS. UseRELAXED_JSON_OPTIONS orCANONICAL_JSON_OPTIONS instead. - If a custom CodecOptions is passed to
RawBSONDocument, itsdocument_class`must beRawBSONDocument. - list_indexes() no longer raises OperationFailure when the collection (or database) does not exist on MongoDB >= 3.0. Instead, it returns an emptyCommandCursor to make the behavior consistent across all MongoDB versions.
- In Python 3, loads() now automatically decodes JSON $binary with a subtype of 0 into bytes instead ofBinary.
- loads() now raises
TypeErrororValueErrorwhen parsing JSON type wrappers with values of the wrong type or any extra keys. - pymongo.cursor.Cursor.close() andpymongo.mongo_client.MongoClient.close()now kill cursors synchronously instead of deferring to a background thread.
- parse_uri() now returns the original value of the
readPreferenceMongoDB URI option instead of the validated read preference mode.
Issues Resolved¶
See the PyMongo 3.5 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 3.4.0 (2016/11/29)¶
Version 3.4 implements the new server features introduced in MongoDB 3.4 and a whole lot more:
Highlights include:
- Complete support for MongoDB 3.4:
- Unicode aware string comparison using Collation.
- Support for the new Decimal128 BSON type.
- A new maxStalenessSeconds read preference option.
- A username is no longer required for the MONGODB-X509 authentication mechanism when connected to MongoDB >= 3.4.
parallel_scan()supports maxTimeMS.- WriteConcern is automatically applied by all helpers for commands that write to the database when connected to MongoDB 3.4+. This change affects the following helpers:
* drop_database()
* create_collection()
* drop_collection()
* aggregate() (when using $out)
* create_indexes()
* create_index()
* drop_indexes()
* drop_indexes()
* drop_index()
*map_reduce()(when output is not “inline”)
*reindex()
* rename()
- Improved support for logging server discovery and monitoring events. Seemonitoring for examples.
- Support for matching iPAddress subjectAltName values for TLS certificate verification.
- TLS compression is now explicitly disabled when possible.
- The Server Name Indication (SNI) TLS extension is used when possible.
- Finer control over JSON encoding/decoding withJSONOptions.
- Allow Code objects to have a scope of
None, signifying no scope. Also allow encoding Code objects with an empty scope (i.e.{}).
Warning
Starting in PyMongo 3.4, bson.code.Code.scope may returnNone, as the default scope is None instead of {}.
Note
PyMongo 3.4+ attempts to create sockets non-inheritable when possible (i.e. it sets the close-on-exec flag on socket file descriptors). Support is limited to a subset of POSIX operating systems (not including Windows) and the flag usually cannot be set in a single atomic operation. CPython 3.4+ implements PEP 446, creating all file descriptors non-inheritable by default. Users that require this behavior are encouraged to upgrade to CPython 3.4+.
Since 3.4rc0, the max staleness option has been renamed from maxStalenessMSto maxStalenessSeconds, its smallest value has changed from twiceheartbeatFrequencyMS to 90 seconds, and its default value has changed fromNone or 0 to -1.
Issues Resolved¶
See the PyMongo 3.4 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 3.3.1 (2016/10/27)¶
Version 3.3.1 fixes a memory leak when decoding elements inside of aRawBSONDocument.
Issues Resolved¶
See the PyMongo 3.3.1 release notes in Jira for the list of resolved issues in this release.
Changes in Version 3.3.0 (2016/07/12)¶
Version 3.3 adds the following major new features:
- C extensions support on big endian systems.
- Kerberos authentication support on Windows using WinKerberos.
- A new
ssl_clrfileoption to support certificate revocation lists. - A new
ssl_pem_passphraseoption to support encrypted key files. - Support for publishing server discovery and monitoring events. Seemonitoring for details.
- New connection pool options
minPoolSizeandmaxIdleTimeMS. - New
heartbeatFrequencyMSoption controls the rate at which background monitoring threads re-check servers. Default is once every 10 seconds.
Warning
PyMongo 3.3 drops support for MongoDB versions older than 2.4. It also drops support for python 3.2 (pypy3 continues to be supported).
Issues Resolved¶
See the PyMongo 3.3 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 3.2.2 (2016/03/15)¶
Version 3.2.2 fixes a few issues reported since the release of 3.2.1, including a fix for using the connect option in the MongoDB URI and support for setting the batch size for a query to 1 when using MongoDB 3.2+.
Issues Resolved¶
See the PyMongo 3.2.2 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 3.2.1 (2016/02/02)¶
Version 3.2.1 fixes a few issues reported since the release of 3.2, including running the mapreduce command twice when calling theinline_map_reduce() method and aTypeError being raised when callingdownload_to_stream(). This release also improves error messaging around BSON decoding.
Issues Resolved¶
See the PyMongo 3.2.1 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 3.2 (2015/12/07)¶
Version 3.2 implements the new server features introduced in MongoDB 3.2.
Highlights include:
- Full support for MongoDB 3.2 including:
- Support for ReadConcern
- WriteConcern is now applied tofind_one_and_replace(),find_one_and_update(), andfind_one_and_delete().
- Support for the new
bypassDocumentValidationoption in write helpers.
- Support for reading and writing raw BSON withRawBSONDocument
Issues Resolved¶
See the PyMongo 3.2 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 3.1.1 (2015/11/17)¶
Version 3.1.1 fixes a few issues reported since the release of 3.1, including a regression in error handling for oversize command documents and interrupt handling issues in the C extensions.
Issues Resolved¶
See the PyMongo 3.1.1 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 3.1 (2015/11/02)¶
Version 3.1 implements a few new features and fixes bugs reported since the release of 3.0.3.
Highlights include:
- Command monitoring support. See monitoring for details.
- Configurable error handling for UnicodeDecodeError. See the
unicode_decode_error_handleroption ofCodecOptions. - Optional automatic timezone conversion when decoding BSON datetime. See the
tzinfooption of CodecOptions. - An implementation of GridFSBucket from the new GridFS spec.
- Compliance with the new Connection String spec.
- Reduced idle CPU usage in Python 2.
Changes in internal classes¶
The private PeriodicExecutor class no longer takes a condition_classoption, and the private thread_util.Event class is removed.
Issues Resolved¶
See the PyMongo 3.1 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 3.0.3 (2015/06/30)¶
Version 3.0.3 fixes issues reported since the release of 3.0.2, including a feature breaking bug in the GSSAPI implementation.
Issues Resolved¶
See the PyMongo 3.0.3 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 3.0.2 (2015/05/12)¶
Version 3.0.2 fixes issues reported since the release of 3.0.1, most importantly a bug that could route operations to replica set members that are not in primary or secondary state when usingPrimaryPreferred orNearest. It is a recommended upgrade for all users of PyMongo 3.0.x.
Issues Resolved¶
See the PyMongo 3.0.2 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 3.0.1 (2015/04/21)¶
Version 3.0.1 fixes issues reported since the release of 3.0, most importantly a bug in GridFS.delete that could prevent file chunks from actually being deleted.
Issues Resolved¶
See the PyMongo 3.0.1 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 3.0 (2015/04/07)¶
PyMongo 3.0 is a partial rewrite of PyMongo bringing a large number of improvements:
- A unified client class. MongoClient is the one and only client class for connecting to a standalone mongod, replica set, or sharded cluster. Migrating from a standalone, to a replica set, to a sharded cluster can be accomplished with only a simple URI change.
- MongoClient is much more responsive to configuration changes in your MongoDB deployment. All connected servers are monitored in a non-blocking manner. Slow to respond or down servers no longer block server discovery, reducing application startup time and time to respond to new or reconfigured servers and replica set failovers.
- A unified CRUD API. All official MongoDB drivers now implement a standard CRUD API allowing polyglot developers to move from language to language with ease.
- Single source support for Python 2.x and 3.x. PyMongo no longer relies on 2to3 to support Python 3.
- A rewritten pure Python BSON implementation, improving performance with pypy and cpython deployments without support for C extensions.
- Better support for greenlet based async frameworks including eventlet.
- Immutable client, database, and collection classes, avoiding a host of thread safety issues in client applications.
PyMongo 3.0 brings a large number of API changes. Be sure to read the changes listed below before upgrading from PyMongo 2.x.
Warning
PyMongo no longer supports Python 2.4, 2.5, or 3.1. If you must use PyMongo with these versions of Python the 2.x branch of PyMongo will be minimally supported for some time.
SONManipulator changes¶
The SONManipulator API has limitations as a technique for transforming your data. Instead, it is more flexible and straightforward to transform outgoing documents in your own code before passing them to PyMongo, and transform incoming documents after receiving them from PyMongo.
Thus the add_son_manipulator() method is deprecated. PyMongo 3’s new CRUD API does not apply SON manipulators to documents passed to bulk_write(),insert_one(),insert_many(),update_one(), orupdate_many(). SON manipulators are notapplied to documents returned by the new methodsfind_one_and_delete(),find_one_and_replace(), andfind_one_and_update().
SSL/TLS changes¶
When ssl is True the ssl_cert_reqs option now defaults tossl.CERT_REQUIRED if not provided. PyMongo will attempt to load OS provided CA certificates to verify the server, raisingConfigurationError if it cannot.
Gevent Support¶
In previous versions, PyMongo supported Gevent in two modes: you could callgevent.monkey.patch_socket() and pass use_greenlets=True toMongoClient, or you could simply callgevent.monkey.patch_all() and omit the use_greenlets argument.
In PyMongo 3.0, the use_greenlets option is gone. To use PyMongo with Gevent simply call gevent.monkey.patch_all().
For more information, see Gevent.
MongoClient changes¶
MongoClient is now the one and only client class for a standalone server, mongos, or replica set. It includes the functionality that had been split intoMongoReplicaSetClient: it can connect to a replica set, discover all its members, and monitor the set for stepdowns, elections, and reconfigs.MongoClient now also supports the fullReadPreference API.
The obsolete classes MasterSlaveConnection, Connection, andReplicaSetConnection are removed.
The MongoClient constructor no longer blocks while connecting to the server or servers, and it no longer raises ConnectionFailure if they are unavailable, nor ConfigurationErrorif the user’s credentials are wrong. Instead, the constructor returns immediately and launches the connection process on background threads. The connect option is added to control whether these threads are started immediately, or when the client is first used.
Therefore the alive method is removed since it no longer provides meaningful information; even if the client is disconnected, it may discover a server in time to fulfill the next operation.
In PyMongo 2.x, MongoClient accepted a list of standalone MongoDB servers and used the first it could connect to:
MongoClient(['host1.com:27017', 'host2.com:27017'])
A list of multiple standalones is no longer supported; if multiple servers are listed they must be members of the same replica set, or mongoses in the same sharded cluster.
The behavior for a list of mongoses is changed from “high availability” to “load balancing”. Before, the client connected to the lowest-latency mongos in the list, and used it until a network error prompted it to re-evaluate all mongoses’ latencies and reconnect to one of them. In PyMongo 3, the client monitors its network latency to all the mongoses continuously, and distributes operations evenly among those with the lowest latency. See load balancing for more information.
The client methods start_request, in_request, and end_requestare removed, and so is the auto_start_request option. Requests were designed to make read-your-writes consistency more likely with the w=0write concern. Additionally, a thread in a request used the same member for all secondary reads in a replica set. To ensure read-your-writes consistency in PyMongo 3.0, do not override the default write concern with w=0, and do not override the default read preference of PRIMARY.
Support for the slaveOk (or slave_okay), safe, andnetwork_timeout options has been removed. UseSECONDARY_PREFERRED instead of slave_okay. Accept the default write concern, acknowledged writes, instead of setting safe=True. Use socketTimeoutMS in place of network_timeout (note that network_timeout was in seconds, where as socketTimeoutMS is milliseconds).
The max_pool_size option has been removed. It is replaced by themaxPoolSize MongoDB URI option. maxPoolSize is now a supported URI option in PyMongo and can be passed as a keyword argument.
The copy_database method is removed, see Copy and Clone Databases for alternatives.
The disconnect method is removed. Useclose() instead.
The get_document_class method is removed. Usecodec_options instead.
The get_lasterror_options, set_lasterror_options, andunset_lasterror_options methods are removed. Write concern options can be passed to MongoClient as keyword arguments or MongoDB URI options.
The get_database() method is added for getting a Database instance with its options configured differently than the MongoClient’s.
The following read-only attributes have been added:
The following attributes are now read-only:
The following attributes have been removed:
document_class(use codec_options instead)host(use address instead)min_wire_versionmax_wire_versionport(use address instead)safe(use write_concern instead)slave_okay(use read_preference instead)tag_sets(use read_preference instead)tz_aware(use codec_options instead)
The following attributes have been renamed:
secondary_acceptable_latency_msis nowlocal_threshold_msand is now read-only.
Cursor changes¶
The conn_id property is renamed to address.
Cursor management changes¶
CursorManager andset_cursor_manager() are no longer deprecated. If you subclass CursorManageryour implementation of close()must now take a second parameter, address. The BatchCursorManager class is removed.
The second parameter to close_cursor()is renamed from _conn_id to address.kill_cursors() now accepts an addressparameter.
Database changes¶
The connection property is renamed toclient.
The following read-only attributes have been added:
The following attributes are now read-only:
Use get_database() for getting a Database instance with its options configured differently than the MongoClient’s.
The following attributes have been removed:
safesecondary_acceptable_latency_msslave_okaytag_sets
The following methods have been added:
The following methods have been changed:
- command(). Support for
as_class,uuid_subtype,tag_sets, andsecondary_acceptable_latency_mshave been removed. You can instead pass an instance ofCodecOptions ascodec_optionsand an instance of a read preference class from read_preferences asread_preference. Thefieldsandcompile_reoptions are also removed. Thefieldsoptions was undocumented and never really worked. Regular expressions are always decoded to Regex.
The following methods have been deprecated:
add_son_manipulator()
The following methods have been removed:
The get_lasterror_options, set_lasterror_options, andunset_lasterror_options methods have been removed. UseWriteConcern withget_database() instead.
Collection changes¶
The following read-only attributes have been added:
The following attributes are now read-only:
Use get_collection() orwith_options() for getting a Collection instance with its options configured differently than the Database’s.
The following attributes have been removed:
safesecondary_acceptable_latency_msslave_okaytag_sets
The following methods have been added:
- bulk_write()
- insert_one()
- insert_many()
- update_one()
- update_many()
- replace_one()
- delete_one()
- delete_many()
- find_one_and_delete()
- find_one_and_replace()
- find_one_and_update()
- with_options()
- create_indexes()
- list_indexes()
The following methods have changed:
- aggregate() now always returns an instance of CommandCursor. See the documentation for all options.
count()now optionally takes a filter argument, as well as other options supported by the count command.- distinct() now optionally takes a filter argument.
- create_index() no longer caches indexes, therefore the
cache_forparameter has been removed. It also no longer supports thebucket_sizeanddrop_dupsaliases forbucketSizeanddropDups.
The following methods are deprecated:
save()insert()update()remove()find_and_modify()ensure_index()
The following methods have been removed:
The get_lasterror_options, set_lasterror_options, andunset_lasterror_options methods have been removed. UseWriteConcern withwith_options() instead.
Changes to find() and find_one()¶
The following find/find_one options have been renamed:
These renames only affect your code if you passed these as keyword arguments, like find(fields=[‘fieldname’]). If you passed only positional parameters these changes are not significant for your application.
- spec -> filter
- fields -> projection
- partial -> allow_partial_results
The following find/find_one options have been added:
- cursor_type (see CursorType for values)
- oplog_replay
- modifiers
The following find/find_one options have been removed:
- network_timeout (use max_time_ms() instead)
- slave_okay (use one of the read preference classes fromread_preferences andwith_options() instead)
- read_preference (use with_options()instead)
- tag_sets (use one of the read preference classes fromread_preferences andwith_options() instead)
- secondary_acceptable_latency_ms (use the
localThresholdMSURI option instead) - max_scan (use the new
modifiersoption instead) - snapshot (use the new
modifiersoption instead) - tailable (use the new
cursor_typeoption instead) - await_data (use the new
cursor_typeoption instead) - exhaust (use the new
cursor_typeoption instead) - as_class (use with_options() withCodecOptions instead)
- compile_re (BSON regular expressions are always decoded toRegex)
The following find/find_one options are deprecated:
- manipulate
The following renames need special handling.
- timeout -> no_cursor_timeout - The default for
timeoutwas True. The default forno_cursor_timeoutis False. If you were previously passing False fort`imeoutyou must pass**True** forno_cursor_timeoutto keep the previous behavior.
errors changes¶
The exception classes UnsupportedOption and TimeoutError are deleted.
gridfs changes¶
Since PyMongo 1.6, methods open and close of GridFSraised an UnsupportedAPI exception, as did the entire GridFile class. The unsupported methods, the class, and the exception are all deleted.
bson changes¶
The compile_re option is removed from all methods that accepted it in bson and json_util. Additionally, it is removed from find(),find_one(),aggregate(),command(), and so on. PyMongo now always represents BSON regular expressions asRegex objects. This prevents errors for incompatible patterns, see PYTHON-500. Use try_compile() to attempt to convert from a BSON regular expression to a Python regular expression object.
PyMongo now decodes the int64 BSON type to Int64, a trivial wrapper around long (in python 2.x) or int (in python 3.x). This allows BSON int64 to be round tripped without losing type information in python 3. Note that if you store a python long (or a python int larger than 4 bytes) it will be returned from PyMongo as Int64.
The as_class, tz_aware, and uuid_subtype options are removed from all BSON encoding and decoding methods. UseCodecOptions to configure these options. The APIs affected are:
This is a breaking change for any application that uses the BSON API directly and changes any of the named parameter defaults. No changes are required for applications that use the default values for these options. The behavior remains the same.
Issues Resolved¶
See the PyMongo 3.0 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 2.9.5 (2017/06/30)¶
Version 2.9.5 works around ssl module deprecations in Python 3.6, and expected future ssl module deprecations. It also fixes bugs found since the release of 2.9.4.
- Use ssl.SSLContext and ssl.PROTOCOL_TLS_CLIENT when available.
- Fixed a C extensions build issue when the interpreter was built with -std=c99
- Fixed various build issues with MinGW32.
- Fixed a write concern bug in
add_user()andremove_user()when connected to MongoDB 3.2+ - Fixed various test failures related to changes in gevent, MongoDB, and our CI test environment.
Issues Resolved¶
See the PyMongo 2.9.5 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 2.9.4 (2016/09/30)¶
Version 2.9.4 fixes issues reported since the release of 2.9.3.
- Fixed __repr__ for closed instances of MongoClient.
- Fixed
MongoReplicaSetClienthandling of uuidRepresentation. - Fixed building and testing the documentation with python 3.x.
- New documentation for TLS and Atlas.
Issues Resolved¶
See the PyMongo 2.9.4 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 2.9.3 (2016/03/15)¶
Version 2.9.3 fixes a few issues reported since the release of 2.9.2 including thread safety issues in ensure_index(),drop_index(), anddrop_indexes().
Issues Resolved¶
See the PyMongo 2.9.3 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 2.9.2 (2016/02/16)¶
Version 2.9.2 restores Python 3.1 support, which was broken in PyMongo 2.8. It improves an error message when decoding BSON as well as fixes a couple other issues including aggregate() ignoringcodec_options andcommand() raising a superfluousDeprecationWarning.
Issues Resolved¶
See the PyMongo 2.9.2 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 2.9.1 (2015/11/17)¶
Version 2.9.1 fixes two interrupt handling issues in the C extensions and adapts a test case for a behavior change in MongoDB 3.2.
Issues Resolved¶
See the PyMongo 2.9.1 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 2.9 (2015/09/30)¶
Version 2.9 provides an upgrade path to PyMongo 3.x. Most of the API changes from PyMongo 3.0 have been backported in a backward compatible way, allowing applications to be written against PyMongo >= 2.9, rather then PyMongo 2.x or PyMongo 3.x. See the PyMongo 3 Migration Guide for detailed examples.
Note
There are a number of new deprecations in this release for features that were removed in PyMongo 3.0.
hostportuse_greenletsdocument_classtz_awaresecondary_acceptable_latency_mstag_setsuuid_subtypedisconnect()alive()
MongoReplicaSetClient:
use_greenletsdocument_classtz_awaresecondary_acceptable_latency_mstag_setsuuid_subtypealive()
secondary_acceptable_latency_mstag_setsuuid_subtype
secondary_acceptable_latency_mstag_setsuuid_subtype
Warning
In previous versions of PyMongo, changing the value ofdocument_class changed the behavior of all existing instances ofCollection:
coll = client.test.test coll.find_one() {u'_id': ObjectId('5579dc7cfba5220cc14d9a18')} from bson.son import SON client.document_class = SON coll.find_one() SON([(u'_id', ObjectId('5579dc7cfba5220cc14d9a18'))])
The document_class setting is now configurable at the client, database, collection, and per-operation level. This required breaking the existing behavior. To change the document class per operation in a forward compatible way usewith_options():
coll.find_one() {u'_id': ObjectId('5579dc7cfba5220cc14d9a18')} from bson.codec_options import CodecOptions coll.with_options(CodecOptions(SON)).find_one() SON([(u'_id', ObjectId('5579dc7cfba5220cc14d9a18'))])
Issues Resolved¶
See the PyMongo 2.9 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 2.8.1 (2015/05/11)¶
Version 2.8.1 fixes a number of issues reported since the release of PyMongo 2.8. It is a recommended upgrade for all users of PyMongo 2.x.
Issues Resolved¶
See the PyMongo 2.8.1 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 2.8 (2015/01/28)¶
Version 2.8 is a major release that provides full support for MongoDB 3.0 and fixes a number of bugs.
Special thanks to Don Mitchell, Ximing, Can Zhang, Sergey Azovskov, and Heewa Barfchin for their contributions to this release.
Highlights include:
- Support for the SCRAM-SHA-1 authentication mechanism (new in MongoDB 3.0).
- JSON decoder support for the new numberLongandnumberLong and numberLongandundefined types.
- JSON decoder support for the $date type as an ISO-8601 string.
- Support passing an index name to hint().
- The
count()method will use a hint if one has been provided through hint(). - A new socketKeepAlive option for the connection pool.
- New generator based BSON decode functions, decode_iter()and decode_file_iter().
- Internal changes to support alternative storage engines like wiredtiger.
Note
There are a number of deprecations in this release for features that will be removed in PyMongo 3.0. These include:
start_request()in_request()end_request()copy_database()error()last_status()previous_error()reset_error_history()MasterSlaveConnection
The JSON format for Timestamp has changed from ‘{“t”: , “i”: }’ to ‘{“$timestamp”: {“t”: , “i”: }}’. This new format will be decoded to an instance ofTimestamp. The old format will continue to be decoded to a python dict as before. Encoding to the old format is no longer supported as it was never correct and loses type information.
Issues Resolved¶
See the PyMongo 2.8 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 2.7.2 (2014/07/29)¶
Version 2.7.2 includes fixes for upsert reporting in the bulk API for MongoDB versions previous to 2.6, a regression in how son manipulators are applied ininsert(), a few obscure connection pool semaphore leaks, and a few other minor issues. See the list of issues resolved for full details.
Issues Resolved¶
See the PyMongo 2.7.2 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 2.7.1 (2014/05/23)¶
Version 2.7.1 fixes a number of issues reported since the release of 2.7, most importantly a fix for creating indexes and manipulating users through mongos versions older than 2.4.0.
Issues Resolved¶
See the PyMongo 2.7.1 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 2.7 (2014/04/03)¶
PyMongo 2.7 is a major release with a large number of new features and bug fixes. Highlights include:
- Full support for MongoDB 2.6.
- A new bulk write operations API.
- Support for server side query timeouts usingmax_time_ms().
- Support for writing aggregate()output to a collection.
- A new
parallel_scan()helper. - OperationFailure and its subclasses now include a details attribute with complete error details from the server.
- A new GridFS find() method that returns aGridOutCursor.
- Greatly improved support for mod_wsgi when using PyMongo’s C extensions. Read Jesse’s blog post for details.
- Improved C extension support for ARM little endian.
Breaking changes¶
Version 2.7 drops support for replica sets running MongoDB versions older than 1.6.2.
Issues Resolved¶
See the PyMongo 2.7 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 2.6.3 (2013/10/11)¶
Version 2.6.3 fixes issues reported since the release of 2.6.2, most importantly a semaphore leak when a connection to the server fails.
Issues Resolved¶
See the PyMongo 2.6.3 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 2.6.2 (2013/09/06)¶
Version 2.6.2 fixes a TypeError problem when max_pool_size=None is used in Python 3.
Issues Resolved¶
See the PyMongo 2.6.2 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 2.6.1 (2013/09/03)¶
Version 2.6.1 fixes a reference leak in the insert() method.
Issues Resolved¶
See the PyMongo 2.6.1 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 2.6 (2013/08/19)¶
Version 2.6 includes some frequently requested improvements and adds support for some early MongoDB 2.6 features.
Special thanks go to Justin Patrin for his work on the connection pool in this release.
Important new features:
- The
max_pool_sizeoption for MongoClientandMongoReplicaSetClientnow actually caps the number of sockets the pool will open concurrently. Once the pool has reaches max_pool_size operations will block waiting for a socket to become available. IfwaitQueueTimeoutMSis set, an operation that blocks waiting for a socket will raise ConnectionFailure after the timeout. By defaultwaitQueueTimeoutMSis not set. See connection pooling for more information. - The
insert()method automatically splits large batches of documents into multiple insert messages based onmax_message_size - Support for the exhaust cursor flag. See find() for details and caveats.
- Support for the PLAIN and MONGODB-X509 authentication mechanisms. See the authentication docs for more information.
- Support aggregation output as a Cursor. Seeaggregate() for details.
Warning
SIGNIFICANT BEHAVIOR CHANGE in 2.6. Previously, max_pool_sizewould limit only the idle sockets the pool would hold onto, not the number of open sockets. The default has also changed, from 10 to 100. If you pass a value for max_pool_size make sure it is large enough for the expected load. (Sockets are only opened when needed, so there is no cost to having a max_pool_size larger than necessary. Err towards a larger value.) If your application accepts the default, continue to do so.
See connection pooling for more information.
Issues Resolved¶
See the PyMongo 2.6 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 2.5.2 (2013/06/01)¶
Version 2.5.2 fixes a NULL pointer dereference issue when decoding an invalid DBRef.
Issues Resolved¶
See the PyMongo 2.5.2 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 2.5.1 (2013/05/13)¶
Version 2.5.1 is a minor release that fixes issues discovered after the release of 2.5. Most importantly, this release addresses some race conditions in replica set monitoring.
Issues Resolved¶
See the PyMongo 2.5.1 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 2.5 (2013/03/22)¶
Version 2.5 includes changes to support new features in MongoDB 2.4.
Important new features:
- Support for GSSAPI (Kerberos).
- Support for SSL certificate validation with hostname matching.
- Support for delegated and role based authentication.
- New GEOSPHERE (2dsphere) and HASHED index constants.
Note
authenticate() now raises a subclass of PyMongoError if authentication fails due to invalid credentials or configuration issues.
Issues Resolved¶
See the PyMongo 2.5 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 2.4.2 (2013/01/23)¶
Version 2.4.2 is a minor release that fixes issues discovered after the release of 2.4.1. Most importantly, PyMongo will no longer select a replica set member for read operations that is not in primary or secondary state.
Issues Resolved¶
See the PyMongo 2.4.2 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 2.4.1 (2012/12/06)¶
Version 2.4.1 is a minor release that fixes issues discovered after the release of 2.4. Most importantly, this release fixes a regression usingaggregate(), and possibly other commands, with mongos.
Issues Resolved¶
See the PyMongo 2.4.1 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 2.4 (2012/11/27)¶
Version 2.4 includes a few important new features and a large number of bug fixes.
Important new features:
- New MongoClient and
MongoReplicaSetClientclasses - these connection classes do acknowledged write operations (previously referred to as ‘safe’ writes) by default.ConnectionandReplicaSetConnectionare deprecated but still support the old default fire-and-forget behavior. - A new write concern API implemented as awrite_concern attribute on the connection,Database, or Collectionclasses.
- MongoClient (and
Connection) now support Unix Domain Sockets. - Cursor can be copied with functions from the copymodule.
- The
set_profiling_level()method now supports aslow_msoption. - The replica set monitor task (used by
MongoReplicaSetClientandReplicaSetConnection) is a daemon thread once again, meaning you won’t have to callclose()before exiting the python interactive shell.
Issues Resolved¶
See the PyMongo 2.4 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 2.3 (2012/08/29)¶
Version 2.3 adds support for new features and behavior changes in MongoDB 2.2.
Important New Features:
- Support for expanded read preferences including directing reads to tagged servers - See secondary reads for more information.
- Support for mongos failover.
- A new aggregate() method to support MongoDB’s new aggregation framework.
- Support for legacy Java and C# byte order when encoding and decoding UUIDs.
- Support for connecting directly to an arbiter.
Warning
Starting with MongoDB 2.2 the getLastError command requires authentication when the server’s authentication features are enabled. Changes to PyMongo were required to support this behavior change. Users of authentication must upgrade to PyMongo 2.3 (or newer) for “safe” write operations to function correctly.
Issues Resolved¶
See the PyMongo 2.3 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 2.2.1 (2012/07/06)¶
Version 2.2.1 is a minor release that fixes issues discovered after the release of 2.2. Most importantly, this release fixes an incompatibility with mod_wsgi 2.x that could cause connections to leak. Users of mod_wsgi 2.x are strongly encouraged to upgrade from PyMongo 2.2.
Issues Resolved¶
See the PyMongo 2.2.1 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 2.2 (2012/04/30)¶
Version 2.2 adds a few more frequently requested features and fixes a number of bugs.
Special thanks go to Alex Grönholm for his contributions to Python 3 support and maintaining the original pymongo3 port. Christoph Simon, Wouter Bolsterlee, Mike O’Brien, and Chris Tompkinson also contributed to this release.
Important New Features:
- Support for Python 3. See Python 3 for more information.
- Support for Gevent - See Gevent for more information.
- Improved connection pooling. See PYTHON-287.
Warning
A number of methods and method parameters that were deprecated in PyMongo 1.9 or older versions have been removed in this release. The full list of changes can be found in the following JIRA ticket:
https://jira.mongodb.org/browse/PYTHON-305
BSON module aliases from the pymongo package that were deprecated in PyMongo 1.9 have also been removed in this release. See the following JIRA ticket for details:
https://jira.mongodb.org/browse/PYTHON-304
As a result of this cleanup some minor code changes may be required to use this release.
Issues Resolved¶
See the PyMongo 2.2 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 2.1.1 (2012/01/04)¶
Version 2.1.1 is a minor release that fixes a few issues discovered after the release of 2.1. You can now useReplicaSetConnectionto run inline map reduce commands on secondaries. Seeinline_map_reduce() for details.
Special thanks go to Samuel Clay and Ross Lawley for their contributions to this release.
Issues Resolved¶
See the PyMongo 2.1.1 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 2.1 (2011/12/07)¶
Version 2.1 adds a few frequently requested features and includes the usual round of bug fixes and improvements.
Special thanks go to Alexey Borzenkov, Dan Crosta, Kostya Rybnikov, Flavio Percoco Premoli, Jonas Haag, and Jesse Davis for their contributions to this release.
Important New Features:
- ReplicaSetConnection -
ReplicaSetConnectioncan be used to distribute reads to secondaries in a replica set. It supports automatic failover handling and periodically checks the state of the replica set to handle issues like primary stepdown or secondaries being removed for backup operations. Read preferences are defined throughReadPreference. - PyMongo supports the new BSON binary subtype 4 for UUIDs. The default subtype to use can be set through
uuid_subtypeThe current default remains OLD_UUID_SUBTYPE but will be changed to UUID_SUBTYPE in a future release. - The getLastError option ‘w’ can be set to a string, allowing for options like “majority” available in newer version of MongoDB.
- Added support for the MongoDB URI options socketTimeoutMS and connectTimeoutMS.
- Added support for the ContinueOnError insert flag.
- Added basic SSL support.
- Added basic support for Jython.
- Secondaries can be used for
count(),distinct(),group(), and querying GridFS. - Added document_class and tz_aware options to
MasterSlaveConnection
Issues Resolved¶
See the PyMongo 2.1 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 2.0.1 (2011/08/15)¶
Version 2.0.1 fixes a regression in GridIn when writing pre-chunked strings. Thanks go to Alexey Borzenkov for reporting the issue and submitting a patch.
Issues Resolved¶
- PYTHON-271: Regression in GridFS leads to serious loss of data.
Changes in Version 2.0 (2011/08/05)¶
Version 2.0 adds a large number of features and fixes a number of issues.
Special thanks go to James Murty, Abhay Vardhan, David Pisoni, Ryan Smith-Roberts, Andrew Pendleton, Mher Movsisyan, Reed O’Brien, Michael Schurter, Josip Delic and Jonas Haag for their contributions to this release.
Important New Features:
- PyMongo now performs automatic per-socket database authentication. You no longer have to re-authenticate for each new thread or after a replica set failover. Authentication credentials are cached by the driver until the application calls
logout(). - slave_okay can be set independently at the connection, database, collection or query level. Each level will inherit the slave_okay setting from the previous level and each level can override the previous level’s setting.
- safe and getLastError options (e.g. w, wtimeout, etc.) can be set independently at the connection, database, collection or query level. Each level will inherit settings from the previous level and each level can override the previous level’s setting.
- PyMongo now supports the
await_dataandpartialcursor flags. If theawait_dataflag is set on atailablecursor the server will block for some extra time waiting for more data to return. Thepartialflag tells a mongos to return partial data for a query if not all shards are available. map_reduce()will accept adictor instance of SON as theoutparameter.- The URI parser has been moved into its own module and can be used directly by application code.
- AutoReconnect exception now provides information about the error that actually occurred instead of a generic failure message.
- A number of new helper methods have been added with options for setting and unsetting cursor flags, re-indexing a collection, fsync and locking a server, and getting the server’s current operations.
API changes:
- If only one host:port pair is specified
Connectionwill make a direct connection to only that host. Please note thatslave_okaymust beTruein order to query from a secondary. - If more than one host:port pair is specified or the
replicasetoption is used PyMongo will treat the specified host:port pair(s) as a seed list and connect using replica set behavior.
Issues Resolved¶
See the PyMongo 2.0 release notes in JIRA for the list of resolved issues in this release.
Changes in Version 1.11 (2011/05/05)¶
Version 1.11 adds a few new features and fixes a few more bugs.
New Features:
- Basic IPv6 support: pymongo prefers IPv4 but will try IPv6. You can also specify an IPv6 address literal in the
hostparameter or a MongoDB URI provided it is enclosed in ‘[’ and ‘]’. - max_pool_size option: previously pymongo had a hard coded pool size of 10 connections. With this change you can specify a different pool size as a parameter to
Connection(max_pool_size=) or in the MongoDB URI (maxPoolSize=). - Find by metadata in GridFS: You can know specify query fields as keyword parameters for get_version() andget_last_version().
- Per-query slave_okay option: slave_okay=True is now a valid keyword argument for find() andfind_one().
API changes:
- validate_collection() now returns a dict instead of a string. This change was required to deal with an API change on the server. This method also now takes the optional
scandataandfullparameters. See the documentation for more details.
Warning
The pool_size, auto_start_request`, and timeout parameters for Connection have been completely removed in this release. They were deprecated in pymongo-1.4 and have had no effect since then. Please make sure that your code doesn’t currently pass these parameters when creating a Connection instance.
Issues resolved¶
- PYTHON-241: Support setting slaveok at the cursor level.
- PYTHON-240: Queries can sometimes permanently fail after a replica set fail over.
- PYTHON-238: error after few million requests
- PYTHON-237: Basic IPv6 support.
- PYTHON-236: Restore option to specify pool size in Connection.
- PYTHON-212: pymongo does not recover after stale config
- PYTHON-138: Find method for GridFS
Changes in Version 1.10.1 (2011/04/07)¶
Version 1.10.1 is primarily a bugfix release. It fixes a regression in version 1.10 that broke pickling of ObjectIds. A number of other bugs have been fixed as well.
There are two behavior changes to be aware of:
- If a read slave raises AutoReconnect
MasterSlaveConnectionwill now retry the query on each slave until it is successful or all slaves have raised AutoReconnect. Any other exception will immediately be raised. The order that the slaves are tried is random. Previously the read would be sent to one randomly chosen slave andAutoReconnect was immediately raised in case of a connection failure. - A Python
longis now always BSON encoded as an int64. Previously the encoding was based only on the value of the field and alongwith a value less than2147483648or greater than-2147483649would always be BSON encoded as an int32.
Issues resolved¶
- PYTHON-234: Fix setup.py to raise exception if any when building extensions
- PYTHON-233: Add information to build and test with extensions on windows
- PYTHON-232: Traceback when hashing a DBRef instance
- PYTHON-231: Traceback when pickling a DBRef instance
- PYTHON-230: Pickled ObjectIds are not compatible between pymongo 1.9 and 1.10
- PYTHON-228: Cannot pickle bson.ObjectId
- PYTHON-227: Traceback when calling find() on system.js
- PYTHON-216: MasterSlaveConnection is missing disconnect() method
- PYTHON-186: When storing integers, type is selected according to value instead of type
- PYTHON-173: as_class option is not propagated by Cursor.clone
- PYTHON-113: Redunducy in MasterSlaveConnection
Changes in Version 1.10 (2011/03/30)¶
Version 1.10 includes changes to support new features in MongoDB 1.8.x. Highlights include a modified map/reduce API including an inline map/reduce helper method, a new find_and_modify helper, and the ability to query the server for the maximum BSON document size it supports.
- added
find_and_modify(). - added
inline_map_reduce(). - changed
map_reduce().
Warning
MongoDB versions greater than 1.7.4 no longer generate temporary collections for map/reduce results. An output collection name must be provided and the output will replace any existing output collection with the same name. map_reduce() now requires the out parameter.
Issues resolved¶
- PYTHON-225:
ObjectIdclass definition should use __slots__. - PYTHON-223: Documentation fix.
- PYTHON-220: Documentation fix.
- PYTHON-219: KeyError in
find_and_modify() - PYTHON-213: Query server for maximum BSON document size.
- PYTHON-208: Fix
Connection__repr__. - PYTHON-207: Changes to Map/Reduce API.
- PYTHON-205: Accept slaveOk in the URI to match the URI docs.
- PYTHON-203: When slave_okay=True and we only specify one host don’t autodetect other set members.
- PYTHON-194: Show size when whining about a document being too large.
- PYTHON-184: Raise DuplicateKeyError for duplicate keys in capped collections.
- PYTHON-178: Don’t segfault when trying to encode a recursive data structure.
- PYTHON-177: Don’t segfault when decoding dicts with broken iterators.
- PYTHON-172: Fix a typo.
- PYTHON-170: Add
find_and_modify(). - PYTHON-169: Support deepcopy of DBRef.
- PYTHON-167: Duplicate of PYTHON-166.
- PYTHON-166: Fixes a concurrency issue.
- PYTHON-158: Add code and err string to
db assertionmessages.
Changes in Version 1.9 (2010/09/28)¶
Version 1.9 adds a new package to the PyMongo distribution,bson. bson contains all of the BSON encoding and decoding logic, and the BSON types that were formerly in the pymongo package. The following modules have been renamed:
pymongo.bson-> bsonpymongo._cbson->bson._cbsonandpymongo._cmessagepymongo.binary-> bson.binarypymongo.code-> bson.codepymongo.dbref-> bson.dbrefpymongo.json_util-> bson.json_utilpymongo.max_key-> bson.max_keypymongo.min_key-> bson.min_keypymongo.objectid-> bson.objectidpymongo.son-> bson.sonpymongo.timestamp-> bson.timestamppymongo.tz_util-> bson.tz_util
In addition, the following exception classes have been renamed:
pymongo.errors.InvalidBSON->bson.errors.InvalidBSONpymongo.errors.InvalidStringData->bson.errors.InvalidStringDatapymongo.errors.InvalidDocument->bson.errors.InvalidDocumentpymongo.errors.InvalidId->bson.errors.InvalidId
The above exceptions now inherit from bson.errors.BSONErrorrather than pymongo.errors.PyMongoError.
Note
All of the renamed modules and exceptions above have aliases created with the old names, so these changes should not break existing code. The old names will eventually be deprecated and then removed, so users should begin migrating towards the new names now.
Warning
The change to the exception hierarchy mentioned above is possibly breaking. If your code is catchingPyMongoError, then the exceptions raised by bson will not be caught, even though they would have been caught previously. Before upgrading, it is recommended that users check for any cases like this.
- the C extension now shares buffer.c/h with the Ruby driver
- bson no longer raises InvalidName, all occurrences have been replaced withInvalidDocument.
- renamed
bson._to_dicts()to decode_all(). - renamed
from_dict()to encode()andto_dict()to decode(). - added batch_size().
- allow updating (some) file metadata after aGridIn instance has been closed.
- performance improvements for reading from GridFS.
- special cased slice with the same start and stop to return an empty cursor.
- allow writing
unicodeto GridFS if anencodingattribute has been specified for the file. - added gridfs.GridFS.get_version().
- scope variables for Code can now be specified as keyword arguments.
- added
readline()toGridOut. - make a best effort to transparently auto-reconnect if a
Connectionhas been idle for a while. - added
list()toSystemJS. - added
file_documentargument to GridOut()to allow initializing from an existing file document. - raise
TimeoutErroreven if thegetLastErrorcommand was run manually and not through “safe” mode. - added
uuidsupport to json_util.
Changes in Version 1.8.1 (2010/08/13)¶
- fixed a typo in the C extension that could cause safe-mode operations to report a failure (SystemError) even when none occurred.
- added a
__ne__()implementation to any class where we define__eq__().
Changes in Version 1.8 (2010/08/05)¶
Version 1.8 adds support for connecting to replica sets, specifying per-operation values for w and wtimeout, and decoding to timezone-aware datetimes.
- fixed a reference leak in the C extension when decoding aDBRef.
- added support for
w,wtimeout, andfsync(and any other options forgetLastError) to “safe mode” operations. - added
nodesproperty. - added a maximum pool size of 10 sockets.
- added support for replica sets.
- DEPRECATED
from_uri()andpaired(), both are supplanted by extended functionality inConnection(). - added tz aware support for datetimes inObjectId,Timestamp and json_utilmethods.
- added drop() helper.
- reuse the socket used for finding the master when a
Connectionis first created. - added support for MinKey,MaxKey andTimestamp to json_util.
- added support for decoding datetimes as aware (UTC) - it is highly recommended to enable this by setting the
tz_awareparameter toConnection()toTrue. - added
network_timeoutoption for individual calls tofind() andfind_one(). - added exists() to check if a file exists in GridFS.
- added support for additional keys in DBRefinstances.
- added code attribute toOperationFailure exceptions.
- fixed serialization of int and float subclasses in the C extension.
Changes in Version 1.7 (2010/06/17)¶
Version 1.7 is a recommended upgrade for all PyMongo users. The full release notes are below, and some more in depth discussion of the highlights is here.
- no longer attempt to build the C extension on big-endian systems.
- added MinKey andMaxKey.
- use unsigned for Timestamp in BSON encoder/decoder.
- support
Trueas"ok"in command responses, in addition to1.0- necessary for server versions >= 1.5.X - BREAKING change toindex_information() to add support for querying unique status and other index information.
- added
document_class, to specify class for returned documents. - added
as_classargument forfind(), and in the BSON decoder. - added support for creating Timestampinstances using a datetime.
- allow
dropTargetargument forrename. - handle aware datetime instances, by converting to UTC.
- added support for max_scan.
- raise FileExists exception when creating a duplicate GridFS file.
- use y2038 for time handling in the C extension - eliminates 2038 problems when extension is installed.
- added
sortparameter tofind() - finalized deprecation of changes from versions <= 1.4
- take any non-dict as an
"_id"query forfind_one() orremove() - added ability to pass a dict for
fieldsargument tofind() (supports"$slice"and field negation) - simplified code to find master, since paired setups don’t always have a remote
- fixed bug in C encoder for certain invalid types (likeCollection instances).
- don’t transparently map
"filename"key tonameattribute for GridFS.
Changes in Version 1.6 (2010/04/14)¶
The biggest change in version 1.6 is a complete re-implementation ofgridfs with a lot of improvements over the old implementation. There are many details and examples of using the new API in this blog post. The old API has been removed in this version, so existing code will need to be modified before upgrading to 1.6.
- fixed issue where connection pool was being shared across
Connectioninstances. - more improvements to Python code caching in C extension - should improve behavior on mod_wsgi.
- added from_datetime().
- complete rewrite of gridfs support.
- improvements to the command() API.
- fixed drop_indexes() behavior on non-existent collections.
- disallow empty bulk inserts.
Changes in Version 1.5.2 (2010/03/31)¶
- fixed response handling to ignore unknown response flags in queries.
- handle server versions containing ‘-pre-‘.
Changes in Version 1.5.1 (2010/03/17)¶
- added
_idproperty forGridFileinstances. - fix for making a
Connection(withslave_okayset) directly to a slave in a replica pair. - accept kwargs forcreate_index() and
ensure_index()to support all indexing options. - add pymongo.GEO2D and support for geo indexing.
- improvements to Python code caching in C extension - should improve behavior on mod_wsgi.
Changes in Version 1.5 (2010/03/10)¶
- added subtype constants to binary module.
- DEPRECATED
optionsargument toCollection() andcreate_collection() in favor of kwargs. - added has_c() to check for C extension.
- added
copy_database(). - added alive to tell when a cursor might have more data to return (useful for tailable cursors).
- added Timestamp to better support dealing with internal MongoDB timestamps.
- added
nameargument forcreate_index() andensure_index(). - fixed connection pooling w/ fork
paired()takes all kwargs that are allowed forConnection().insert()returns list for bulk inserts of size one.- fixed handling of datetime.datetime instances injson_util.
- added
from_uri()to support MongoDB connection uri scheme. - fixed chunk number calculation when unaligned in gridfs.
- command() takes a string for simple commands.
- added
system_jshelper for dealing with server-side JS. - don’t wrap queries containing
"$query"(support manual use of"$min", etc.). - added GridFSError as base class forgridfs exceptions.
Changes in Version 1.4 (2010/01/17)¶
Perhaps the most important change in version 1.4 is that we have decided to no longer support Python 2.3. The most immediate reason for this is to allow some improvements to connection pooling. This will also allow us to use some new (as in Python 2.4 ;) idioms and will help begin the path towards supporting Python 3.0. If you need to use Python 2.3 you should consider using version 1.3 of this driver, although that will no longer be actively supported.
Other changes:
- move
"_id"to front only for top-level documents (fixes some corner cases). update()andremove()return the entire response to the lastError command when safe isTrue.- completed removal of things that were deprecated in version 1.2 or earlier.
- enforce that collection names do not contain the NULL byte.
- fix to allow using UTF-8 collection names with the C extension.
- added PyMongoError as base exception class for all errors. this changes the exception hierarchy somewhat, and is a BREAKING change if you depend onConnectionFailure being a IOErroror InvalidBSON being a ValueError, for example.
- added DuplicateKeyError for calls to
insert()orupdate()withsafeset toTrue. - removed
thread_util. - added
add_user()andremove_user()helpers. - fix for
authenticate()when using non-UTF-8 names or passwords. - minor fixes for
MasterSlaveConnection. - clean up all cases where ConnectionFailureis raised.
- simplification of connection pooling - makes driver ~2x faster for simple benchmarks. see connection pooling for more information.
- DEPRECATED
pool_size,auto_start_requestandtimeoutparameters toConnection. DEPRECATEDstart_request(). - use
socket.sendall(). - removed
from_xml()as it was only being used for some internal testing - also eliminates dependency onelementtree. - implementation of
update()in C. - deprecate
_command()in favor ofcommand(). - send all commands without wrapping as
{"query": ...}. - support string as
keyargument togroup()(keyf) and run all groups as commands. - support for equality testing for Codeinstances.
- allow the NULL byte in strings and disallow it in key names or regex patterns
Changes in Version 1.3 (2009/12/16)¶
- DEPRECATED running
group()aseval(), also changed default forgroup()to running as a command - remove
pymongo.cursor.Cursor.__len__(), which was deprecated in 1.1.1 - needed to do this aggressively due to it’s presence breaking Django template for loops - DEPRECATED
host(),port(),connection(),name(),database(),name() andfull_name() in favor ofhost,port,connection,name,database,name andfull_name, respectively. The deprecation schedule for this change will probably be faster than usual, as it carries some performance implications. - added
disconnect()
Changes in Version 1.2.1 (2009/12/10)¶
- added Changelog to docs
- added
setup.py doc --testto run doctests for tutorial, examples - moved most examples to Sphinx docs (and remove from _examples/_directory)
- raise InvalidId instead ofTypeError when passing a 24 character string toObjectId that contains non-hexadecimal characters
- allow
unicodeinstances for ObjectId init
Changes in Version 1.2 (2009/12/09)¶
specparameter forremove()is now optional to allow for deleting all documents in aCollection- always wrap queries with
{query: ...}even when no special options - get around some issues with queries on fields namedquery - enforce 4MB document limit on the client side
- added
map_reduce()helper - seeAggregation - added distinct() method onCursor instances to allow distinct with queries
- fix for __getitem__() afterskip()
- allow any UTF-8 string in BSON encoder, not just ASCII subset
- added generation_time
- removed support for legacy ObjectIdformat - pretty sure this was never used, and is just confusing
- DEPRECATED
url_encode()andurl_decode()in favor ofstr()and ObjectId(), respectively - allow oplog.$main as a valid collection name
- some minor fixes for installation process
- added support for datetime and regex in json_util
Changes in Version 1.1.2 (2009/11/23)¶
- improvements to
insert()speed (using C for insert message creation) - use random number for request_id
- fix some race conditions with AutoReconnect
Changes in Version 1.1.1 (2009/11/14)¶
- added
multiparameter forupdate() - fix unicode regex patterns with C extension
- added distinct()
- added
databasesupport for DBRef - added json_util with helpers for encoding / decoding special types to JSON
- DEPRECATED
pymongo.cursor.Cursor.__len__()in favor ofcount()withwith_limit_and_skipset toTruedue to performance regression - switch documentation to Sphinx
Changes in Version 1.1 (2009/10/21)¶
- added
__hash__()for DBRef andObjectId - bulk
insert()works with any iterable - fix ObjectId generation when usingmultiprocessing
- added collection
- added
network_timeoutparameter forConnection() - DEPRECATED
slave_okayparameter for individual queries - fix for
safemode when multi-threaded - added
safeparameter forremove() - added
tailableparameter for find()
Changes in Version 1.0 (2009/09/30)¶
- fixes for
MasterSlaveConnection - added
finalizeparameter forgroup() - improvements to
insert()speed - improvements to gridfs speed
- added __getitem__() and
__len__()forCursor instances
Changes in Version 0.16 (2009/09/16)¶
Changes in Version 0.15.2 (2009/09/09)¶
- documentation changes only
Changes in Version 0.15.1 (2009/09/02)¶
- various performance improvements
- API CHANGE no longer need to specify direction forcreate_index() and
ensure_index()when indexing a single key - support for encoding tuple instances as listinstances
Changes in Version 0.15 (2009/08/26)¶
- fix string representation of ObjectIdinstances
- added
timeoutparameter forfind() - allow scope for
reducefunction ingroup()
Changes in Version 0.14.2 (2009/08/24)¶
- minor bugfixes
Changes in Version 0.14.1 (2009/08/21)¶
seek()andtell()for (read mode)GridFileinstances
Changes in Version 0.14 (2009/08/19)¶
Changes in Version 0.13 (2009/07/29)¶
- better
MasterSlaveConnectionsupport - API CHANGE
insert()andsave()both return inserted_id - DEPRECATED passing an index name tohint()
Changes in Version 0.12 (2009/07/08)¶
- improved ObjectId generation
- added AutoReconnect exception for when reconnection is possible
- make gridfs thread-safe
- fix for gridfs with non ObjectId
_id
Changes in Version 0.11.3 (2009/06/18)¶
- don’t allow NULL bytes in string encoder
- fixes for Python 2.3
Changes in Version 0.11.2 (2009/06/08)¶
- PEP 8
- updates for
group() - VS build
Changes in Version 0.11.1 (2009/06/04)¶
- fix for connection pooling under Python 2.5
Changes in Version 0.11 (2009/06/03)¶
- better build failure detection
- driver support for selecting fields in sub-documents
- disallow insertion of invalid key names
- added
timeoutparameter forConnection()
Changes in Version 0.10.3 (2009/05/27)¶
- fix bug with large limit()
- better exception when modules get reloaded out from underneath the C extension
- better exception messages when calling aCollection orDatabase instance
Changes in Version 0.10.2 (2009/05/22)¶
- support subclasses of dict in C encoder
Changes in Version 0.10.1 (2009/05/18)¶
- alias
Connectionaspymongo.Connection - raise an exception rather than silently overflowing in encoder
Changes in Version 0.10 (2009/05/14)¶
- added
ensure_index()
Changes in Version 0.9.7 (2009/05/13)¶
- allow sub-collections of $cmd as validCollection names
- add version as pymongo.version
- add
--no_extcommand line option to setup.py