Python bson 库 : get bson alias

标签 python mongodb types pymongo bson

我正在寻找如下所示的 type_of 方法:

import bson
bson.type_of(42)  # it should return "int".
bson.type_of("hello")  # it should return "string".
type("hello").__name__   # it returns "str" and not "string" therefore no suitable.

我想要的结果(intstring)是 BSON 别名(参见 https://docs.mongodb.com/manual/reference/bson-types/)。

这个方法type_of是否已经存在?

如果它返回类型的数字(1 表示 Double,2 表示 String ...)就可以了。

谢谢,

编辑: 这是我目前的解决方案:

type_of = {
    type(2.5).__name__: "number",
    type(1).__name__: "number",
    type("a_string").__name__: "string",
    type([1, 2]).__name__: "array",
    type(True).__name__: "bool"
}  # type_of[type(3).__name__] returns "number"

最佳答案

如果您想要实际的 BSON 类型(数字不是 bson 类型),我不确定是否有办法。我已经使用这个函数来帮助理清 python 将对象编码为:

def what_bson_type(input):
    import bson
    return bson._ELEMENT_GETTER[bson.BSON.encode({"t":input})[4]].__name__[5:]

注意:这些“类型”与 bson 规范不匹配,但它们在过去足以帮助我。

>>> what_bson_type("hi")
'string'
>>> what_bson_type(1)
'int'
>>> what_bson_type(sys.maxint)
'int64'
>>> what_bson_type(True)
'boolean'
>>> what_bson_type({"a":"b"})
'object'
>>> what_bson_type(1.2)
'float'
>>> what_bson_type([1,2])
'array'
>>> what_bson_type(re.compile(r".*"))
'regex'
>>> what_bson_type(bson.Binary("hi"))
'binary'

关于Python bson 库 : get bson alias,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41959847/

相关文章:

python - MongoEngine - 通过 id 从 ListField 中提取引用

python - 如何允许用户输入各种各样的内容并让它们在 numpy 数组中工作?

types - 为什么最好使用 Glib 数据类型(例如 `gint` 而不是 `int` )?

python - 火车功能内部和外部的结果不同

python - 为 Python 3 mac 安装 PyQt4

python - QML Charts 导致启动时崩溃

node.js - MongoDB 无法 $unset 特定字段;自动 _id 字段位于末尾

python - 无错误地停止 Python 代码

mysql - 使用哪个数据库来存储键值(数组)对

c - 通过 1 个函数用不同的数据类型填充数组