【问题标题】:How to Store dictionary as array object within a mongodb field如何在 mongodb 字段中将字典存储为数组对象
【发布时间】:2021-01-03 08:07:28
【问题描述】:

我有 MongoDB 集合,其中包含许多文档,每个文档的字段看起来像图片中显示的那样。问题在于“搜索”字段。它的值存储为字符串,因此我无法查询像 {"searched.image_hash":"some_value"} 这样的值。我使用 python 将值存储到 MongoDB 中。在python中,在mongo中存储为“searched”的变量“to_search”实际上是一个字典。我不确定为什么“to_search”变量中的字典作为字符串存储在 mongodb“搜索”字段中。关于如何将字典作为对象数组存储在 mongodb 中的任何建议?

我在python中使用的代码如下

i have many other keys going into dictionary 'di'
        di['account_id'] = acc_num
        di['searched']= to_search
        di['breakdown_queried'] = breakdown_to_query
        di['combination']= [ele for ele in to_search.keys()]
        di['ad_ids'] = ad_ids
        di['date'] = date.today()
        lo_str= ''
        di = {k: str(v) for k, v in di.items()}
        mongo_obj_remote.client["dev"]["ad_stats_tracker"].delete_one({"_id": {"$in": [di['_id']]}})
        di_key_li = ['_id','account_id','date', 'combination','searched', 'ad_ids','breakdown_queried']
        mongo_obj_remote.insert_single_document("dev", "ad_stats_tracker", {key: di[key] for key in di_key_li})

【问题讨论】:

  • 你能显示保存searched字段的代码吗?
  • @balderman 嗨,我的问题完全不同,我很困惑为什么字典存储为字符串而不是对象。我的意图是将它存储为对象,以便我可以进行这样的查询 {"searched.image_hash":"some_value"}

标签: python mongodb pymongo


【解决方案1】:

如果您在to_search 中的数据是python dict(而不是看起来像的字符串),那么pymongo 驱动程序会将数据存储为BSON“对象”,而不是字符串;有效地,这会在存储在集合中的文档中创建一个子文档。

查看您的数据,我建议您的 to_search 实际上是一个字符串;该格式对 dict 无效,因为它包含一个集合(无论如何 pymongo 都无法将其存储在 mongodb 中)。

您可以在插入数据之前使用少量调试代码进行检查:

print(type(di['searched']))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-20
    • 1970-01-01
    • 2012-11-24
    • 1970-01-01
    • 2013-09-02
    相关资源
    最近更新 更多