如何在mongodb中使用`$或`

时间:2016-01-29 07:25:05

标签: python mongodb pymongo

我是MongoDB的新用户,当我使用$or运算符时,我遇到了一个问题。

这是我的代码:

for element in table1.find():
        total += 1
        result = table2.find_one({'guanZhi' : element['guanZhi'], 
                                  'name'    : element['name'],
                                  'minZu'   : element['minZu'],
                                  'keJu'    : element['keJu']})

        if result and (element['qiFen'] == result['qiFen'] or 
                       element['qiFen'] == result['qiFenHuo']):
            pass
        else:
            failed += 1

关于(element['qiFen'] == result['qiFen'] or element['qiFen'] == result['qiFenHuo']),我想使用$or,但我不知道如何编写代码。

我这样改了:

for element in table1.find({'ji': ""}):
        if table2.find_one({'guanZhi' : element['guanZhi'],
                            'name'    : element['name'],
                            'minZu'   : element['minZu'],
                            'nian'    : element['nian'],
                            '$or'     : [{'qiFen' : element['qiFen']}, {'qiFenHuo': element['qiFen']}]}):
            match.write(formatElement(element))
        else:
            no_match.write(formatElement(element))
            failed += 1

但是我很困惑,这段代码看起来不错吗? 我想要:

(guanZhi' : element['guanZhi']) and 
('name' : element['name'])      and 
('minZu'   : element['minZu'])  and 
('keJu': element['keJu'])       and 
({'qiFen' : element['qiFen']}   or  {'qiFenHuo': element['qiFen']})

1 个答案:

答案 0 :(得分:0)

如果我理解正确,我认为您需要包含$ AND运算符和$ OR运算符......

我理解你想要得到的是: “你指定的文件”     AND({'qiFen':element ['qiFen']}          或'qiFenHuo':元素['qiFen']})

如果是这样的话......尝试将代码与这样的代码结合起来:

db.inventory.find( {
    $and : [
        // YOUR CODE HERE,
        { $or : [ { sale : true }, { qty : { $lt : 20 } } ] }
    ]
} )