gpt4 book ai didi

python - pymongo:搜索字典或操作

转载 作者:可可西里 更新时间:2023-11-01 09:28:20 26 4
gpt4 key购买 nike

我正在使用下面的代码试图获取所有记录,“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 是正确的 $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

关于python - pymongo:搜索字典或操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8859874/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com