PyMongo 4迁移指南#
PyMongo 4.0带来了许多改进,同时也带来了一些突破性的变化。本指南提供了将现有应用程序从PyMongo 3.x迁移到4.x或编写同时支持PyMongo 3.x和4.x的库的路线图。
《白夜追凶3》#
任何成功迁移的第一步都需要升级到或至少需要升级到最新版本的PyMongo 3.x。如果您的项目有Requirements s.txt文件,请添加“pymongo>=3.12,<4.0”行,直到您完全迁移到PyMongo 4为止。PyMongo 4.0中的大多数关键新方法和选项都已在PyMongo 3.12中向后移植,从而使迁移更加容易。
备注
希望升级到4.x的PyMongo 2.x用户必须首先升级到PyMongo 3.x,方法是遵循 PyMongo 3 Migration Guide 。
Python3.6+#
PyMongo 4.0不再支持Python2.7、3.4和3.5。想要升级到4.x的用户必须首先升级到3.6.2+。从Python2升级的用户应该参考 Python 3常见问题解答 。
启用弃用警告#
DeprecationWarning
是由PyMongo 4.0中删除的大多数方法引发的。确保启用运行时警告,以查看应用程序中使用了已弃用的函数和方法的位置:
python -Wd <your application>
警告也可以更改为错误::
python -Wd -Werror <your application>
备注
并非所有不推荐使用的功能都会引发 DeprecationWarning
在使用的时候。看见 Removed features with no migration path 。
MongoReplicaSetClient#
已删除 MongoReplicaSetClient
。从PyMongo 3.0开始, MongoReplicaSetClient
已完全相同于 pymongo.mongo_client.MongoClient
。应用程序只需替换 MongoReplicaSetClient
使用 pymongo.mongo_client.MongoClient
并得到相同的行为。
MongoClient#
directConnection
缺省值为False#
directConnection
URI选项和关键字参数 MongoClient
默认为 False
而不是 None
,允许自动发现副本集。这意味着,如果您想要直接连接到单个服务器,则必须通过 directConnection=True
作为URI选项或关键字参数。
如果你看到任何 ServerSelectionTimeoutError
从PyMongo 3升级到4.x后,您可能需要添加 directConnection=True
在创建客户端时。以下是一些错误示例:
pymongo.errors.ServerSelectionTimeoutError: mongo_node2: [Errno 8] nodename nor servname
provided, or not known,mongo_node1:27017
ServerSelectionTimeoutError: No servers match selector "Primary()", Timeout: 30s,
Topology Description: ...
此外,在以下情况下,服务器发回的Hello命令的“isWritablePrimary”属性将始终为True directConnection=False
**
>>> client.admin.command('hello')['isWritablePrimary']
True
将删除waitQueueMultiple参数#
删除了 waitQueueMultiple
关键字参数为 MongoClient
并被移除 pymongo.errors.ExceededMaxWaiters
。与其使用 waitQueueMultiple
若要限制队列,请限制应用程序中线程池的大小。
将删除socketKeepAlive参数#
删除了 socketKeepAlive
关键字参数为 MongoClient
。现在,PyMongo始终启用TCP Keep Alive。有关更多信息,请参阅 documentation 。
已重命名的URI选项#
几个不推荐使用的URI选项已重命名为 URI options specification 。下表汇总了旧的选项名称及其重命名的等价物。一些重命名的选项与被替换的选项具有不同的语义,如“迁移说明”一栏中所述。
旧URI选项 |
已重命名的URI选项 |
迁移说明 |
---|---|---|
ssl_pem_passphrase |
Tls认证密钥文件密码 |
|
ssl_ca_certs |
TlsCAFile |
|
ssl_crlfile |
TlsCRL文件 |
|
ssl_match_hostname |
TlsAllowInvalidHostname |
|
ssl_cert_reqs |
TlsAllowInvalid证书 |
而不是 |
ssl_certfile |
Tls认证密钥文件 |
Instead of using |
ssl_keyfile |
||
J |
日记本 |
|
WTimeout |
WTimeoutMS |
MongoClient.fsync已删除#
已删除 pymongo.mongo_client.MongoClient.fsync()
。运行 fsync command 直接与 command()
取而代之的是。例如::
client.admin.command('fsync', lock=True)
MongoClient.unlock已删除#
已删除 pymongo.mongo_client.MongoClient.unlock()
。运行 fsyncUnlock command 直接与 command()
取而代之的是。例如::
client.admin.command('fsyncUnlock')
MongoClient.IS_LOCKED已删除#
已删除 pymongo.mongo_client.MongoClient.is_locked
。运行 currentOp command 直接与 command()
取而代之的是。例如::
is_locked = client.admin.command('currentOp').get('fsyncLock')
MongoClient.database_NAMES已删除#
已删除 pymongo.mongo_client.MongoClient.database_names()
。使用 list_database_names()
取而代之的是。代码如下::
names = client.database_names()
可以更改为::
names = client.list_database_names()
MongoClient.max_bson_size/max_message_size/max_write_batch_size已删除#
已删除 pymongo.mongo_client.MongoClient.max_bson_size
, pymongo.mongo_client.MongoClient.max_message_size
,以及 pymongo.mongo_client.MongoClient.max_write_batch_size
。这些助手在进入时是不正确的 loadBalanced=true mode
并且在具有混合版本的集群中不明确。使用 hello command 以从远程服务器获取权威值。代码如下::
max_bson_size = client.max_bson_size
max_message_size = client.max_message_size
max_write_batch_size = client.max_write_batch_size
可以更改为::
doc = client.admin.command('hello')
max_bson_size = doc['maxBsonObjectSize']
max_message_size = doc['maxMessageSizeBytes']
max_write_batch_size = doc['maxWriteBatchSize']
删除MongoClient.Event_Listeners和其他配置选项帮助器#
将删除以下客户端配置选项帮助器:- pymongo.mongo_client.MongoClient.event_listeners
。- pymongo.mongo_client.MongoClient.max_pool_size
。- pymongo.mongo_client.MongoClient.max_idle_time_ms
。- pymongo.mongo_client.MongoClient.local_threshold_ms
。- pymongo.mongo_client.MongoClient.server_selection_timeout
。- pymongo.mongo_client.MongoClient.retry_writes
。- pymongo.mongo_client.MongoClient.retry_reads
。
这些帮手已经被替换为 pymongo.mongo_client.MongoClient.options
。代码如下::
client.event_listeners
client.local_threshold_ms
client.server_selection_timeout
client.max_pool_size
client.min_pool_size
client.max_idle_time_ms
可以更改为::
client.options.event_listeners
client.options.local_threshold_ms
client.options.server_selection_timeout
client.options.pool_options.max_pool_size
client.options.pool_options.min_pool_size
client.options.pool_options.max_idle_time_seconds
tz_aware
defaults to False
#
这个 tz_aware
参数为 JSONOptions
现在默认为 False
而不是 True
。 bson.json_util.loads()
现在默认情况下将DateTime解码为naive::
>>> from bson import json_util
>>> s = '{"dt": {"$date": "2022-05-09T17:54:00Z"}}'
>>> json_util.loads(s)
{'dt': datetime.datetime(2022, 5, 9, 17, 54)}
保留PyMongo 3行为集 tz_aware=True
,例如::
>>> from bson import json_util
>>> opts = json_util.JSONOptions(tz_aware=True)
>>> s = '{"dt": {"$date": "2022-05-09T17:54:00Z"}}'
>>> json_util.loads(s, json_options=opts)
{'dt': datetime.datetime(2022, 5, 9, 17, 54, tzinfo=<bson.tz_util.FixedOffset object at 0x7fd1ebc1add0>)}
进行此更改是为了匹配的默认行为 CodecOptions
和 bson.decode
。
MongoClient在以下时间后无法执行操作 close()
#
MongoClient
关闭后不能执行任何操作。之前的行为将简单地重新连接。但是,现在您必须创建一个新实例。
当提供多个URI时,MongoClient会引发异常#
MongoClient
现在引发一个 ConfigurationError
当多个URI传递到 hosts
争论。
在登录信息中给出未转义的百分号时,MongoClient会引发异常#
MongoClient
现在引发一个 InvalidURI
当它在用户名和密码中遇到未转义的百分号时发生异常。
数据库#
将删除Database.vernate和Database.logout#
已删除 pymongo.database.Database.authenticate()
和 pymongo.database.Database.logout()
。在同一客户端上对多个用户进行身份验证与MongoDB 3.6+中对逻辑会话的支持冲突。要作为多个用户进行身份验证,请创建多个实例 MongoClient
。代码如下::
client = MongoClient()
client.admin.authenticate('user1', 'pass1')
client.admin.authenticate('user2', 'pass2')
可以更改为::
client1 = MongoClient(username='user1', password='pass1')
client2 = MongoClient(username='user2', password='pass2')
或者,创建包含应用程序所需的所有身份验证权限的单个用户。
已删除Database.Collection_NAMES#
已删除 pymongo.database.Database.collection_names()
。使用 list_collection_names()
取而代之的是。代码如下::
names = client.collection_names()
non_system_names = client.collection_names(include_system_collections=False)
可以更改为::
names = client.list_collection_names()
non_system_names = client.list_collection_names(filter={"name": {"$regex": r"^(?!system\\.)"}})
已删除Database.Current_op#
已删除 pymongo.database.Database.current_op()
。使用 aggregate()
相反,使用 $currentOp aggregation pipeline stage 。代码如下::
ops = client.admin.current_op()['inprog']
可以更改为::
ops = list(client.admin.aggregate([{'$currentOp': {}}]))
将删除Database.addUser#
已删除 pymongo.database.Database.add_user()
这在PyMongo 3.6中已被弃用。使用 createUser command 或 updateUser command 取而代之的是。要创建用户::
db.command("createUser", "admin", pwd="password", roles=["dbAdmin"])
要创建只读用户:
db.command("createUser", "user", pwd="password", roles=["read"])
要更改密码::
db.command("updateUser", "user", pwd="newpassword")
或更改角色:
db.command("updateUser", "user", roles=["readWrite"])
将删除Database.Remove_User#
已删除 pymongo.database.Database.remove_user()
这在PyMongo 3.6中已被弃用。使用 dropUser command 相反::
db.command("dropUser", "user")
数据库.配置文件_级别已删除#
已删除 pymongo.database.Database.profiling_level()
这在PyMongo 3.12中已被弃用。使用 profile command 取而代之的是。代码如下::
level = db.profiling_level()
可以更改为::
profile = db.command('profile', -1)
level = profile['was']
将删除Database.set_PROFILING_LEVEL#
已删除 pymongo.database.Database.set_profiling_level()
这在PyMongo 3.12中已被弃用。使用 profile command 取而代之的是。代码如下::
db.set_profiling_level(pymongo.ALL, filter={'op': 'query'})
可以更改为::
res = db.command('profile', 2, filter={'op': 'query'})
数据库配置文件_INFO已删除#
已删除 pymongo.database.Database.profiling_info()
这在PyMongo 3.12中已被弃用。查询 'system.profile' collection 取而代之的是。代码如下::
profiling_info = db.profiling_info()
可以更改为::
profiling_info = list(db['system.profile'].find())
Database.__bool__ 引发未实现的错误#
Database
现在在作为布尔值求值时引发错误。代码如下::
if database:
可以更改为::
if database is not None:
现在,您必须显式地与NONE进行比较。
集合#
Collection.Aggregate的useCursor选项已删除#
删除了 useCursor
选项 aggregate()
这在PyMongo 3.6中已被弃用。该选项仅在从MongoDB 2.4升级到MongoDB 2.6时才是必需的。
Collection.Insert已删除#
已删除 pymongo.collection.Collection.insert()
。使用 insert_one()
或 insert_many()
取而代之的是。
代码如下::
collection.insert({'doc': 1})
collection.insert([{'doc': 2}, {'doc': 3}])
可以更改为::
collection.insert_one({'my': 'document'})
collection.insert_many([{'doc': 2}, {'doc': 3}])
Collection.save已删除#
已删除 pymongo.collection.Collection.save()
。应用程序将获得更好的性能 insert_one()
要插入新文档并执行以下操作 update_one()
要更新现有文档,请执行以下操作。代码如下::
doc = collection.find_one({"_id": "some id"})
doc["some field"] = <some value>
db.collection.save(doc)
可以更改为::
result = collection.update_one({"_id": "some id"}, {"$set": {"some field": <some value>}})
如果性能不是问题,重构是站不住脚的, save
可以像这样实现::
def save(doc):
if '_id' in doc:
collection.replace_one({'_id': doc['_id']}, doc, upsert=True)
return doc['_id']
else:
res = collection.insert_one(doc)
return res.inserted_id
Collection.UPDATE已删除#
已删除 pymongo.collection.Collection.update()
。使用 update_one()
要更新单个文档或 update_many()
更新多个文档。代码如下::
collection.update({}, {'$set': {'a': 1}})
collection.update({}, {'$set': {'b': 1}}, multi=True)
可以更改为::
collection.update_one({}, {'$set': {'a': 1}})
collection.update_many({}, {'$set': {'b': 1}})
Collection.Remove已删除#
已删除 pymongo.collection.Collection.remove()
。使用 delete_one()
要删除单个文档或 delete_many()
要删除多个文档,请执行以下操作。代码如下::
collection.remove({'a': 1}, multi=False)
collection.remove({'b': 1})
可以更改为::
collection.delete_one({'a': 1})
collection.delete_many({'b': 1})
Collection.find_and_Modify已删除#
已删除 pymongo.collection.Collection.find_and_modify()
。使用 find_one_and_update()
, find_one_and_replace()
,或 find_one_and_delete()
取而代之的是。代码如下::
updated_doc = collection.find_and_modify({'a': 1}, {'$set': {'b': 1}})
replaced_doc = collection.find_and_modify({'b': 1}, {'c': 1})
deleted_doc = collection.find_and_modify({'c': 1}, remove=True)
可以更改为::
updated_doc = collection.find_one_and_update({'a': 1}, {'$set': {'b': 1}})
replaced_doc = collection.find_one_and_replace({'b': 1}, {'c': 1})
deleted_doc = collection.find_one_and_delete({'c': 1})
Collection.count和Cursor.count已删除#
已删除 pymongo.collection.Collection.count()
和 pymongo.cursor.Cursor.count()
。使用 count_documents()
或 estimated_document_count()
取而代之的是。代码如下::
ntotal = collection.count({})
nmatched = collection.count({'price': {'$gte': 10}})
# Or via the Cursor.count api:
ntotal = collection.find({}).count()
nmatched = collection.find({'price': {'$gte': 10}}).count()
可以更改为::
ntotal = collection.estimated_document_count()
nmatched = collection.count_documents({'price': {'$gte': 10}})
备注
当从迁移时 count()
至 count_documents()
必须替换以下查询运算符:
运算符 |
更换 |
---|---|
$Where |
|
$NEAR |
$geoWithin with $center; i.e.
|
$NEARE球体 |
$geoWithin with $centerSphere; i.e.
|
Collection.Initialize_Ordered_Bulk_op和Initialize_Unordered_Bulk_op被删除#
已删除 pymongo.collection.Collection.initialize_ordered_bulk_op()
和 pymongo.bulk.BulkOperationBuilder
。使用 pymongo.collection.Collection.bulk_write()
取而代之的是。代码如下::
batch = coll.initialize_ordered_bulk_op()
batch.insert({'a': 1})
batch.find({'a': 1}).update_one({'$set': {'b': 1}})
batch.find({'a': 2}).upsert().replace_one({'b': 2})
batch.find({'a': 3}).remove()
result = batch.execute()
可以更改为::
coll.bulk_write([
InsertOne({'a': 1}),
UpdateOne({'a': 1}, {'$set': {'b': 1}}),
ReplaceOne({'a': 2}, {'b': 2}, upsert=True),
DeleteOne({'a': 3}),
])
Collection.Initialize_Unordered_Bulk_op已删除#
已删除 pymongo.collection.Collection.initialize_unordered_bulk_op()
。使用 pymongo.collection.Collection.bulk_write()
取而代之的是。代码如下::
batch = coll.initialize_unordered_bulk_op()
batch.insert({'a': 1})
batch.find({'a': 1}).update_one({'$set': {'b': 1}})
batch.find({'a': 2}).upsert().replace_one({'b': 2})
batch.find({'a': 3}).remove()
result = batch.execute()
可以更改为::
coll.bulk_write([
InsertOne({'a': 1}),
UpdateOne({'a': 1}, {'$set': {'b': 1}}),
ReplaceOne({'a': 2}, {'b': 2}, upsert=True),
DeleteOne({'a': 3}),
], ordered=False)
Collection.group已删除#
已删除 pymongo.collection.Collection.group()
。此方法在PyMongo 3.5中已弃用。MongoDB 4.2删除了 group command 。使用 aggregate()
与 $group
而是上台表演。
Collection.map_Reduced和Collection.inline_map_Reduce将被删除#
已删除 pymongo.collection.Collection.map_reduce()
和 pymongo.collection.Collection.inline_map_reduce()
。迁移到 aggregate()
或运行 mapReduce command 直接与 command()
取而代之的是。有关此迁移的更多指导,请参阅:
Collection.确保已删除_INDEX#
已删除 pymongo.collection.Collection.ensure_index()
。使用 create_index()
或 create_indexes()
取而代之的是。请注意 ensure_index
维护最近创建的索引的内存缓存,而较新的方法没有。应用程序应避免频繁调用 create_index()
或 create_indexes()
。代码如下::
def persist(self, document):
collection.ensure_index('a', unique=True)
collection.insert_one(document)
可以更改为::
def persist(self, document):
if not self.created_index:
collection.create_index('a', unique=True)
self.created_index = True
collection.insert_one(document)
Collection.reindex已删除#
已删除 pymongo.collection.Collection.reindex()
。运行 reIndex command 直接取而代之。代码如下::
>>> result = database.my_collection.reindex()
可以更改为::
>>> result = database.command('reIndex', 'my_collection')
将移除修改器参数#
删除了 modifiers
参数来自 find()
, find_one()
, find_raw_batches()
,以及 Cursor()
。而是将选项直接传递给该方法。代码如下::
cursor = coll.find({}, modifiers={
"$comment": "comment",
"$hint": {"_id": 1},
"$min": {"_id": 0},
"$max": {"_id": 6},
"$maxTimeMS": 6000,
"$returnKey": False,
"$showDiskLoc": False,
})
可以更改为::
cursor = coll.find(
{},
comment="comment",
hint={"_id": 1},
min={"_id": 0},
max={"_id": 6},
max_time_ms=6000,
return_key=False,
show_record_id=False,
)
对于min/max,提示参数是必需的#
这个 hint
选项现在是必填项 min
或 max
查询使用 find()
以确保查询使用正确的索引。例如,代码如下::
cursor = coll.find({}, min={'x', min_value})
可以更改为::
cursor = coll.find({}, min={'x', min_value}, hint=[('x', ASCENDING)])
Collection.__bool__ 引发未实现的错误#
Collection
现在在作为布尔值求值时引发错误。代码如下::
if collection:
可以更改为::
if collection is not None:
现在,您必须显式地与NONE进行比较。
Collection.find返回带有空投影的整个文档#
Empty projections (eg {} or []) for
find()
, and
find_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.
To ensure that behavior remains consistent, code like this:
coll.find({}, projection={})
可以更改为::
coll.find({}, projection={"_id":1})
已删除SONManipator#
已删除 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
,以及 pymongo.database.Database.incoming_manipulators
。
删除了 manipulate
参数来自 find()
, find_one()
,以及 Cursor()
。
这个 pymongo.son_manipulator.SONManipulator
API作为一种转换数据的技术存在局限性,在PyMongo 3.0中已被弃用。相反,在将传出文档传递到PyMongo之前,在您自己的代码中转换传出文档,并在从PyMongo接收到传入文档之后转换传入文档,这会更加灵活和直接。
或者,如果您的应用程序使用 SONManipulator
API将自定义类型转换为BSON,则 TypeCodec
和 TypeRegistry
API可能是一个合适的替代方案。有关更多信息,请参见 custom type example 。
SON().items()
现在又回来了 dict_items
对象。#
items()
现在返回一个 dict_items
对象而不是列表。
SON().iteritems()
已删除。#
SON.iteritems()
现在被移除了。如下所示的代码::
for k, v in son.iteritems():
现在可以替换为如下代码::
for k, v in son.items():
IsMaster已删除#
已删除 pymongo.ismaster.IsMaster
。使用 pymongo.hello.Hello
取而代之的是。
NotMasterError已删除#
已删除 NotMasterError
。使用 NotPrimaryError
取而代之的是。
证书错误已删除#
已删除 CertificateError
。从PyMongo 3.0开始,此错误在内部处理,不会在应用程序中出现。
已删除PYMOGO。GEOHAYSTACK#
已删除 pymongo.GEOHAYSTACK
。替换为“GeoHayStack”或创建一个2D索引,并使用$GeoNear或$GeoWiThin。请参阅https://dochub.mongodb.org/core/4.4-deprecate-geoHaystack.
UUIDLegacy已删除#
已删除 bson.binary.UUIDLegacy
。使用 bson.binary.Binary.from_uuid()
取而代之的是。代码如下::
uu = uuid.uuid4()
uuid_legacy = UUIDLegacy(uu)
可以更改为::
uu = uuid.uuid4()
uuid_legacy = Binary.from_uuid(uu, PYTHON_LEGACY)
默认JSON模式从传统模式更改为宽松模式#
将默认的JSON编码表示从遗留更改为松弛。的json_mode参数 bson.json_util.dumps
现在默认为 RELAXED_JSON_OPTIONS
。
GridFS更改#
DISABLE_MD5参数已删除#
删除了 disable_md5 选项 GridFSBucket
和 GridFS
。GridFS不再生成校验和。需要文件摘要的应用程序应该在GridFS外部实现它,并将其与其他文件元数据一起存储。例如::
import hashlib
my_db = MongoClient().test
fs = GridFSBucket(my_db)
with fs.open_upload_stream("test_file") as grid_in:
file_data = b'...'
sha356 = hashlib.sha256(file_data).hexdigest()
grid_in.write(file_data)
grid_in.sha356 = sha356 # Set the custom 'sha356' field
请注意,对于大文件,可能需要以块为单位计算校验和,以避免一次加载整个文件所需的过多内存。
已删除无迁移路径的功能#
CURSOR_MANAGER支持已删除#
已删除 pymongo.cursor_manager.CursorManager
, pymongo.cursor_manager
,以及 pymongo.mongo_client.MongoClient.set_cursor_manager()
。
MongoClient.CLOSE_CURSOR已删除#
已删除 pymongo.mongo_client.MongoClient.close_cursor()
和 pymongo.mongo_client.MongoClient.kill_cursors()
。取而代之的是用以下命令关闭游标 pymongo.cursor.Cursor.close()
或 pymongo.command_cursor.CommandCursor.close()
。
将删除Database.val、Database.system_js和SystemJS#
已删除 eval()
, system_js
和 SystemJS
。MongoDB 3.0中弃用了val命令,并在MongoDB 4.2中将其删除。MongoDB 4.2+不能替代val。
然而,在MongoDB<=4.0上,代码如下::
>>> result = database.eval('function (x) {return x;}', 3)
可以更改为::
>>> from bson.code import Code
>>> result = database.command('eval', Code('function (x) {return x;}'), args=[3]).get('retval')
将删除Database.Error、Database.last_Status、Database.Precision_Error和Database.Reset_Error_HISTORY#
已删除 pymongo.database.Database.error()
, pymongo.database.Database.last_status()
, pymongo.database.Database.previous_error()
,以及 pymongo.database.Database.reset_error_history()
。这些方法已经过时:所有MongoDB写操作都使用确认的写关注,并在默认情况下报告它们的错误。这些方法在PyMongo 2.8中已弃用。
Collection.PARALLEL_SCAN已删除#
已删除 parallel_scan()
。MongoDB 4.2删除了 parallelCollectionScan command 。这是无可替代的。
已删除pymongo。消息帮助器#
已删除 pymongo.message.delete()
, pymongo.message.get_more()
, pymongo.message.insert()
, pymongo.message.kill_cursors()
, pymongo.message.query()
,以及 pymongo.message.update()
。
名称是pymongo.drive_info.DriverInfo的必需参数#
name
现在是的必需参数 pymongo.driver_info.DriverInfo
班级。
DBRef BSON/JSON解码行为#
更改了的BSON和JSON解码行为 DBRef
中概述的行为匹配 DBRef specification 版本1.0。具体地说,PyMongo现在只将子文档解码为 DBRef
当且仅当,它包含两者 $ref
和 $id
字段和 $ref
, $id
,以及 $db
字段的类型正确。否则,文档将照常返回。以前,任何包含 $ref
字段将被解码为 DBRef
。
默认情况下,对UUID进行编码会引发错误#
默认设置 uuid_representation
为 CodecOptions
, JSONOptions
,以及 MongoClient
已从 bson.binary.UuidRepresentation.PYTHON_LEGACY
至 bson.binary.UuidRepresentation.UNSPECIFIED
。正在尝试对 uuid.UUID
实例设置为BSON或JSON,现在默认情况下会生成错误。如果您以前使用的是UUID,则需要设置 uuid_representation
至 bson.binary.UuidRepresentation.PYTHON_LEGACY
以避免数据损坏。如果您没有UUID,则应设置 bson.binary.UuidRepresentation.STANDARD
。如果没有显式设置值,则在尝试对 uuid.UUID
**
ValueError: cannot encode native uuid.UUID with UuidRepresentation.UNSPECIFIED. UUIDs can be manually converted...
看见 处理UUID数据 了解更多细节。
其他BSON类实现 __slots__
#
Int64
, MinKey
, MaxKey
, Timestamp
, Regex
,以及 DBRef
现在实施 __slots__
以减少内存使用量。这意味着它们的属性是固定的,并且不能在运行时将新属性添加到对象。