如何在MongoDB Atlas 中获取'full database name'?
How to get the 'full database name' in MongoDB Atlas?
我希望在创建索引时使用可预测的名称,以应对 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 时如何获得 'full database name'?大多数时候,前缀似乎对 Mongo Shell 和 pymongo 是透明的。
共享集群中的数据库确实会发生这种情况。但是添加的前缀对于您在集群中创建的所有数据库将保持不变。
这意味着您可以计算此唯一前缀的字节数并根据唯一前缀创建索引,并且不超过 127 字节的最大字节长度。
谢谢
我希望在创建索引时使用可预测的名称,以应对 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 时如何获得 'full database name'?大多数时候,前缀似乎对 Mongo Shell 和 pymongo 是透明的。
共享集群中的数据库确实会发生这种情况。但是添加的前缀对于您在集群中创建的所有数据库将保持不变。
这意味着您可以计算此唯一前缀的字节数并根据唯一前缀创建索引,并且不超过 127 字节的最大字节长度。
谢谢