如何在mongodb字段中将字典存储为数组对象

时间:2020-09-16 13:18:34

标签: python mongodb pymongo

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

enter image description here

我在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})

1 个答案:

答案 0 :(得分:0)

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

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

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

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