python – pymongo:搜索字典或操作

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

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)

解决方法:

@qiao是正确的$或语法是正确的继承人一个完整的例子:

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
上一篇:python – 从mongodb集合中提取所有_id的最佳方法


下一篇:python – flask 0.10 mongo在应用程序上下文之外工作