代码之家  ›  专栏  ›  技术社区  ›  SC990987

如何在Pymongo find方法中使用条件语句

  •  0
  • SC990987  · 技术社区  · 1 年前

    因此,我试图在我的数据库中搜索,看看哪些文档通过了特定的测试。词典的结构是

    dict = {
           'test_results':{
                            'test1':1, ## either 0 or 1 depending on failing/passing respectively 
                            'test2':0,
                            ...,
                            'testN':1
            },
           'identifier': ID 
    }
    

    所以我想进行搜索,打印测试2失败的文档的所有标识符。

    我试着写一个查询,比如

    list(mycol.find({},{
        "_id":0,
        "$expr":{
            "$cond": {
                'if': {"$lt":["$test_results.test2",1]},
                'then': {"ID":"$identifier"}
            }
        }
    }))
    

    我本以为这会给我测试2结果为0的文档的标识符,但这只会给我带来错误

    FieldPath field names may not start with '$'. Consider using $getField or $setField., full error: {'ok': 0.0, 'errmsg': "FieldPath field names may not start with '$'. Consider using $getField or $setField.", 'code': 16410, 'codeName': 'Location16410'}

    我想知道我的查询/任何建议做错了什么,以提高搜索效率。

    1 回复  |  直到 1 年前
        1
  •  0
  •   aneroid    1 年前

    的第二个参数 find 是一个投影,因此它必须在顶级具有字段名。你把 $expr 但你可能想要 ID 。因此,要用最少的更改修复现有查询,请执行以下操作:

    list(mycol.find({},{
      "_id": 0,
      "ID": {
        "$cond": {
          "if": { "$lt": ["$test_results.test2", 1] },
          "then": "$identifier",
          "else": None
        }
      }
    }))
    

    JS等效于 Mongo Plaground .

    但有了这个查询,你会得到 None 对于它经过的那些ID;这可能是没有用的。请参阅操场上的第二份文件 test2: 1 所以结果是 ID: null .

    然而,你说 “给我测试2导致0的文档的标识符” ,所以这应该是你的一部分 发现 标准

    list(mycol.find(
      { "test_results.test2": 0 },  # the query
      # the projection
      {
        "_id": 0,
        "ID": "$identifier"
      }
    ))
    

    正如您所看到的,这是一个简单得多的查询&预测 Mongo Playground

    除非你有负值,否则应该像对待 0 ,检查是否与相等 0 而不是“小于1”。如果您确实需要“小于1”的检查,请执行以下操作:

    list(mycol.find(
      { "test_results.test2": {"$lt": 1} },
      # the projection
      {
        "_id": 0,
        "ID": "$identifier"
      }
    ))