Python 在mongodb集合中搜索动态字段
如果要在mongodb集合中搜索特定字段,我的命令将如下所示:Python 在mongodb集合中搜索动态字段,python,mongodb,pymongo,Python,Mongodb,Pymongo,如果要在mongodb集合中搜索特定字段,我的命令将如下所示: db.collection.find({ name : "John"}) 如果我想使字段名成为动态的,该命令是什么 例如: db.collection.find({ <Dyanmic field variable> : <Value>}) db.collection.find({:}) 或者是否有其他方法可以实现此功能?只需使用变量代替字典键: name = 'field_name' db.coll
db.collection.find({ name : "John"})
如果我想使字段名成为动态的,该命令是什么
例如:
db.collection.find({ <Dyanmic field variable> : <Value>})
db.collection.find({:})
或者是否有其他方法可以实现此功能?只需使用变量代替字典键:
name = 'field_name'
db.collection.find({name : "John"})
当您在不知道数据类型的情况下尝试时,就会出现问题。因此,为了处理这个问题,我使用了以下方法:
def multi_row_single_field_update(self, crieteriafldnm, crieteriafldtyp, updtfldnm, updtfldval, updtfldtyp):
try:
criteria = raw_input('\nEnter ' + crieteriafldnm + ' to update\n')
if crieteriafldtyp == 'int':
count = self.my_connect.find({str(crieteriafldnm): int(criteria)}).count()
else:
count = self.my_connect.find({str(crieteriafldnm): str(criteria)}).count()
updt_criteria = int(criteria) if updtfldtyp == 'int' else str(criteria)
self.my_connect.update(
{"$atomic": 1},
{str(crieteriafldnm): updt_criteria},
{"$set": {str(updtfldnm): str(updtfldval)}},
upsert=False, multi=True
)
您的意思是希望在代码中使用存储在变量中的字段名,例如“查找所有文档,其中存储在变量值
fieldname
中的字段名为22
”?或者您想在MongoDB中同时搜索多个字段名,例如“查找名称以'duck\
开头的字段值为44
的所有文档”?我认为这不是关于OP问题的答案。试着关注他的需要,这将是IMHO动态创建dict,然后执行db.collection.find(dinamically\u build\u dict)
。