我希望在创建索引时有可预测的名称,以便应对 v4.2 之前的 MongoDB 中索引名称的长度限制,这是我编写的方法:
import pymongo
from pymongo.collection import Collection
def _ensure_index(collection: Collection, keys, **kwargs):
if isinstance(keys, str):
keys = [(keys, pymongo.ASCENDING)]
name = kwargs.pop("name", pymongo.helpers._gen_index_name(keys))
full_qualified_name = "%s.%s.$%s" % (collection.database.name, collection.name, name)
if share.common.ARGS.get("--truncate-index-names", False) and len(full_qualified_name) > 127:
# when using MongoDB prior to 4.2
hex_crc = hex(binascii.crc32(full_qualified_name.encode("utf-8")))[2:]
name = "%s_%s" % (
name[: -(len(full_qualified_name) - 127 + len("_" + hex_crc))],
hex_crc,
)
index_name = collection.create_index(keys, name=name, **kwargs)
print("Created index %s.%s %s" % (collection.name, index_name, keys))
return index_name
当我使用 MongoDB 社区服务器时,它可以完美地工作。但是,使用 MongoDB Atlas 时,我得到了pymongo.errors.OperationFailure:从索引名称“5d78be1aa6f2393b01ff006f_mydb.mycol.$index_keys_bla_bla_9392152b”生成的命名空间名称太长(最大 127 字节)
。
似乎完全限定的数据库名称在 MongoDB Atlas 中有一个前缀(我猜 Atlas 中的一个 MongoDB 服务器实际上可以由多个实例共享,这就是为什么它们可以提供便宜的副本等,但需要数据库名称的前缀来确保独特性)。所以我想知道在使用Atlas时如何获得“完整的数据库名称”?大多数时候,前缀对于 Mongo Shell 和 pymongo 来说似乎是透明的。
最佳答案
共享集群中的数据库确实会发生这种情况。但添加的前缀对于您在集群中创建的所有数据库将保持不变。
这意味着您可以计算此唯一前缀的字节数,并针对该唯一前缀创建索引,并且不超过最大字节长度(127 字节)。
谢谢
关于mongodb - 如何在MongoDB Atlas中获取 'full database name'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58814521/