在pymongo中$and运算符的正确用法是什么?

2024-05-23 17:51:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样的结构:

>>>test_3.find_one({"humsavar.Disease": {"$exists": True}}, 
{"humsavar":True, "_id":False})

{u'humsavar': [{u'Association': u'Polymorphism',
   u'Disease': u'-',
   u'Gene names': u'DTWD1',
   u'Mutate aa': u'Pro',
   u'Position aa': 9,
   u'Reference aa': u'Leu',
   u'Substitution': u'Leu9Pro',
   u'SwissVarID': u'VAR_036757',
   u'Uniprot': u'Q8N5C7',
   u'dbSNP': u'rs11539522'},
  {u'Association': u'Polymorphism',
   u'Disease': u'Pyruvate dehydrogenase lipoic acid synthetase deficiency',
   u'Gene names': u'DTWD1',
   u'Mutate aa': u'Lys',
   u'Position aa': 13,
   u'Reference aa': u'Glu',
   u'Substitution': u'Glu13Lys',
   u'SwissVarID': u'VAR_036758',
   u'Uniprot': u'Q8N5C7',
   u'dbSNP': u'rs11539519'}]}

我是否应该使用以下查询搜索humsavar with a Disease和dbSNP中的所有文档?在

^{pr2}$

我希望这个查询也有类似的数字:

test_3.find({"$and": [{"humsavar.Disease": {"$ne": u'-', "$ne":None, "$exists":  True}},
 {"humsavar.dbSNP": {"$ne": u'-', "$ne": None, "$exists":  True}}]},
 {"humsavar":True, "_id": False}).count()

但结果是8499


Tags: testidfalsetruenamesexistsfindaa
2条回答

来自MongoDB文档的^{}用法。在

MongoDB provides an implicit AND operation when specifying a comma separated list of expressions. Using an explicit AND with the $and operator is necessary when the same field or operator has to be specified in multiple expressions.

您只需要对重复的字段名使用$and运算符。humsaver.Diseasehumsaver.dbSNP和{}的条件将是隐式的。(尽管使用$and将得到相同的结果)。在

test_3.find(
    {"humsavar.Disease": 
        {'$and': [
            {"$ne": u'-'},
            { "$ne":None},
            { "$exists":  True}
        ]}
    },
    {"humsavar.dbSNP": 
        {'$and':[
            {"$ne": u'-'},
            { "$ne": None},
            { "$exists":  True}
        ]},
    },
    {"humsavar":True, "_id": False}
).count()

上一个查询返回的文档太多,因为在python中,不能在dict中包含重复的键,例如:

{"$ne": u'-', "$ne":None, "$exists":  True}

{cd1>的第二个结果将覆盖第一个dict

^{pr2}$

这一切都发生在python解释器层中,然后传递给pymongo驱动程序。在

如果要在一个字段上有多个$ne条件,可以使用^{}(“not in”)运算符。在

相关问题 更多 >