簡體   English   中英

pymongo查詢未返回結果

[英]pymongo query not returning results

我在查詢時遇到麻煩,我試圖在許多字段上使用find contains查詢,這是我的代碼。 我將不勝感激任何幫助。

def loadContact(search):
    myQuery = {'username' : {'$ne' : session['username']},\
               '$and' : [{'$or' : [\
                     {'username' : '/.*' + search + '.*/i'},\
                     {'surname' : '/.*' + search + '.*/i'},\
                     {'firstName' : '/.*' + search + '.*/i'},\
                     {'email' : '/.*' + search + '.*/i'},\
                     {'company' : '/.*' + search + '.*/i'}]}]}
    cursor = db.users.find(myQuery)
    payload = []
    content = {}
    for doc in cursor:
        #this is mocked up code for this question so you can see more clearly
        content = {'username' : cursor[0], 'firstName' : cursor[1]}
        payload.append(content)

    return payload

值得一提的是,循環不會進行迭代,如果循環不進行迭代,則循環的內容現在並不十分重要。

因為我需要任何字符串值的具體值,所以這里是任何字符串的具體值:

session['username'] = "username" 
loadContact(): loadContact("string")

帶有斜線的字符串不會像您期望的那樣被解釋為分隔正則表達式。 您需要使用$regex運算符或使用Python正則表達式對象。 您還不需要使用$and此處,因為所有術語都是隱式“與”的。

myQuery = {'username' : {'$ne' : session['username']},
           '$or' : [
                 {'username' : {'$regex' : search, '$options': 'i'}},
                 {'surname' : {'$regex' : search, '$options': 'i'}},
                 {'firstName' : {'$regex' : search, '$options': 'i'}},
                 {'email' : {'$regex' : search, '$options': 'i'}},
                 {'company' : {'$regex' : search, '$options': 'i'}}]}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM