如何在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时如何获得“完整数据库名称”?前缀似乎大多数时候对Mongo Shell和pymongo都是透明的。

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

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

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

谢谢

本文链接:https://www.f2er.com/3119055.html

大家都在问