【发布时间】:2019-11-12 08:13:58
【问题描述】:
我希望在创建索引时使用可预测的名称,以应对 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: namespace name generated from index name "5d78be1aa6f2393b01ff006f_mydb.mycol.$index_keys_bla_bla_9392152b" is too long (127 byte max)。
似乎完全限定的数据库名称在 MongoDB Atlas 中有一个前缀(我猜 Atlas 中的一个 MongoDB 服务器实际上可以由多个实例共享,这就是它们可以提供廉价副本等的原因,但需要数据库名称的前缀来确保唯一性)。所以我想知道在使用 Atlas 时如何获得“完整的数据库名称”?大多数时候,前缀似乎对 Mongo Shell 和 pymongo 是透明的。
【问题讨论】:
标签: mongodb pymongo mongodb-atlas