如何使用 PyMongo 从 Python 字典(到 MongoDB)存储小数和日期

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

这是我用来测试的代码片段。我试图确定当您使用字典与 JSON 样式以及使用变量时会发生什么。

    from decimal import * 
    from pymongo import MongoClient
    
    my_int_a = "21"
    my_int_b = 21
    
   row_dict = {}
    row_dict['key'] = 'my string (default)'
    row_dict['myInteger'] = int(21)
    row_dict['myInteger2'] = 21
    row_dict['myInteger3'] = my_int_a
    row_dict['myInteger4'] = my_int_b
    # row_dict['myCurrencyDecimal'] = Decimal(25.97)
    row_dict['myCurrencyDouble'] = 25.97
    row_dict['myDateInsertedFmt'] = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S.000Z")
    row_dict['myDateInsertedNow'] = datetime.datetime.now()

    db_collection_test_datatypes.insert_one(row_dict)    db_collection_test_datatypes.insert_one(row_dict)
    
    
    json_dict = {
        'key': 'my json key',
        'myInteger': 21,
        'myCurrencyDouble': 25.97
    }
    db_collection_test_datatypes.insert_one(json_dict)

这是我在数据库中看到的:

{
    "_id": ObjectId("653052a351416c5223bbeee7"),
    "key": "my string (default)",
    "myInteger": NumberInt("21"),
    "myInteger2": NumberInt("21"),
    "myInteger3": "21",
    "myInteger4": NumberInt("21"),
    "myCurrencyDouble": 25.97,
    "myDateInsertedFmt": "2023-10-18T16:48:19.000Z",
    "myDateInsertedNow": ISODate("2023-10-18T16:48:19.411Z")
}    and 
    {
      "_id": ObjectId("65305109485c0394d26e8983"),
      "key": "my json key",
      "myInteger": NumberInt("21"),
      "myCurrencyDouble": 25.97
    }

注意:格式化日期没有 ISODate 包装器。我在某个地方看到上面是用于在 MongoDB 中存储日期的格式。因此,如果我有一个日期,我需要将其加载到日期类型。 (自从我第一次发布这个问题以来,我已经多次更改了这个问题,它不是 ISODATE)。

当我尝试使用小数(上面已注释掉)时,出现此错误:

bson.errors.InvalidDocument:无法编码对象:Decimal('25.969999999999998863131622783839702606201171875'),类型:

我必须存储浮点值吗?

我的问题的第 2 部分,如果我使用带引号的 JSON,那么数字是 存储为字符串? JSON 似乎缺乏标准,所以有人建议 将所有值放在引号中。

python python-3.x mongodb decimal pymongo
1个回答
0
投票

对于以字符串形式存储的日期,请注意,显示的名称

strftime
返回一个字符串。

pymongo 库包含日期时间的自动格式化功能,并将其直接存储为 Mongo 中的正确格式。

同样适用于 float(不是十进制)和 int 不需要强制转换,因为类型在 Python 中是动态分配的。

我建议尽可能多地使用 float,如果您确实需要使用

Decimal
,那么您需要将其转换为
Decimal128
。 该主题已相关,请参阅:Pymongo: Cannot Encode object of typedecimal.Decimal?

如果您还有其他问题,请告诉我,我很乐意为您提供帮助

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