如何在MongoDB Atlas中获得“完整数据库名称”?

问题描述 投票:3回答:1

我想在创建索引时使用可预测的名称,以应对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
1个回答
1
投票

共享数据库中的数据库确实会发生这种情况。但是添加的前缀对于您在集群中创建的所有数据库将保持不变。

这意味着您可以计算此唯一前缀的字节数,并相对于该唯一前缀创建索引,并且不超过最大字节长度,即127个字节。

© www.soinside.com 2019 - 2024. All rights reserved.