pymongo:搜索字典或操作

时间:2012-01-14 03:15:45

标签: python mongodb pymongo

我正在使用下面的代码试图获取所有记录,“user_name”字段或“text”字段包含指定的关键字,它看起来像pymongo将操作视为AND,如何指定pymongo来对待它是“OR”操作吗?

search_dict = {}

text_regex = ".*" + key + ".*";
text_reg = re.compile(text_regex,re.IGNORECASE)
search_dict["text"] = text_reg

user_name_regex = ".*" + key + ".*";
user_name_reg = re.compile(user_name_regex,re.IGNORECASE)
search_dict["user_name"] = user_name_reg

records = gLife_Article_Collection.find(search_dict)

2 个答案:

答案 0 :(得分:4)

@qiao是正确的,$or语法是正确的,这是一个完整的例子:

import re
from pymongo import Connection
connection = Connection()
db = connection.test_database
db.regex_test.drop()

# Create some sample docs
db.regex_test.save({"user_name": "Rozza", "text": "Writing an example for Bin Chen based on qiao's answer"})
db.regex_test.save({"user_name": "qiao", "text": "Answering Bin Chen's question"})
db.regex_test.save({"user_name": "Bin Chen", "text": "Reading rozza's answer"})

# Do a regex $or query simple example
search_dict = {"$or": [
    {"user_name": {"$regex": "^Rozza"}}, 
    {"text": {"$regex": "rozza"}}
]}
assert db.regex_test.find(search_dict).count() == 2

# Do a regex $or query with re.compile
search_dict = {"$or": [
    {"user_name": re.compile("*.Rozza.*", re.IGNORECASE)}, 
    {"text": re.compile("*.Rozza.*", re.IGNORECASE)}
]}
assert db.regex_test.find(search_dict).count() == 2

答案 1 :(得分:1)

特殊键$or将允许您进行逻辑组合,请参阅官方MongoDB文档:http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24or

search_dict = {'$or': [{'text': text_reg}, {'user_name': user_name_reg}]}
records = gLife_Article_Collections.find(search_dict)