Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在mongodb集合中搜索动态字段_Python_Mongodb_Pymongo - Fatal编程技术网

Python 在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

如果要在mongodb集合中搜索特定字段,我的命令将如下所示:

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)