我有一个JSON文件,我正在使用MongoDB数据库使用PyMongo
检索该文件。
通过执行以下操作,我将Python游标转换为列表:
db = mongo_client.test_db
table = db.test_table
doc = list(table.find())
现在我要做的是检查列表是否包含一个特定的字符串,如果包含了,它应该只保留字符串的一个子字符串。
列表:
doc=[{'_id': ObjectId('5f45228293d7b757bcbd2d67'),'features': [DBRef('featId', ObjectId('5f452e3793d7b757bcbd2d88'))]}]
因此,目前我正在使用下面的代码来检查列表中是否存在DBRef
,这个列表工作得很好。但我不太清楚要用什么替换print语句,以便只保留ObjectId
。
if "DBRef" in str(doc):
print("its here") #remove the dbref and only keep alphanumeric value
else:
print("not here") #do nothing to the list
预期输出(如果在列表中找到DBRef ):
doc=[{'_id': ObjectId('5f45228293d7b757bcbd2d67'),'features': ObjectId('5f452e3793d7b757bcbd2d88')}]
发布于 2021-03-03 03:16:32
据我所知,列表中有一本字典,因此您只需更新其中一些值即可。
不确定doc变量的期望输出是什么,列表中有多少条数据集等等,但是,下面是我得出的结论:
中现有的dict
doc指的是列表的第一个元素。
“‘’python
备选案文1:
#regex version in case saving ObjectId as bson.objectid is not required
import re
object_value = re.search("DBRef\('featId', ObjectId\((.*?)\)", str(doc[0]['features'])).group(1)
d1 = {'features': f'ObjectId({object_value})'}
doc[0].update(d1)
备选案文2:
#accessing the required value directly and saving it as ObjectId
from bson.objectid import ObjectId
from bson.dbref import DBRef
object_value_no_regex = doc[0]['features'][0].id
d1 = {'features': ObjectId(object_value_no_regex)}
doc[0].update(d1)
谢谢!
https://stackoverflow.com/questions/66454685
复制相似问题