我使用python3.7.1(默认值,2018年12月14日,19:28:38)和pymongo3.7.2。在
在mongodb中,这是有效的:
db.collection.find(
{$and:[
{"field":{$regex:"bon?"}},
{"field":{$not:{$regex:"bon souple"}}},
{"field":{$not:{$regex:"bon léger"}}}
]}
)
所以在pymongo我做了同样的事情:
^{pr2}$但它表示pymongo.errors.OperationFailure: $regex has to be a string
。在
所以我按照建议尝试了这个here:
^{3}$我注意到,即使没有特殊字符,它也表示同样的错误:
liste_reg=[
{'field': {'$regex': {'$not': re.compile('bon souple')}}} #where no special char is present
]
rslt=list(
db.collection.find({"$and":liste_reg})
)
所以我尝试使用"/"
作为:
liste_reg=[
{'field': {'$regex': {'$not':'/bon souple/'}}} #where no special char is present
#even tried re.compile('/bon souple/')
]
rslt=list(
db.collection.find({"$and":liste_reg})
)
同样的错误pymongo.errors.OperationFailure: $regex has to be a string
仍然发生。在
我能做什么?在
我对解决方案研究的一些更新
问题的核心似乎在于$not
,因为当我这样做时:
liste_reg=[{'field': {'$regex': 'bon?'}}]
rslt=list(
db.collection.find({"$and":liste_reg})
)
len(rslt)#gives 23 013, what is ok.
没有错误。在
一些样品
按照艾玛的要求,我可以给出一个样本,它会在mongo中明确我的请求。 通常情况下,我必须在现场使用这些方法:
对我来说,主要的问题是我的蜘蛛没有正确解析,因为我没有为此编写足够强大的脚本。 我得到的不是“苯教”,而是这样的结果:
{"_id":"ID1",
"field":"bon\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\tnon",
...}
这是其他许多错误解析之间的一个例子。
所以这就是为什么我想要以"bon?"
开头的结果,而不是"bon souple"
或{\n
或{
作为样品:
[{"_id":"ID1",
"field":"bon\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\tnon"},
{"_id":"ID2",
"field":"bon\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tpremière"},
{"_id":"ID3",
"field":"bon\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t2ème"},
{"_id":"ID4",
"field":"bon souple"},
{"_id":"ID5",
"field":"bon léger"}]
尝试使用带有否定前瞻性的字符串文本。只要“bon”后面有回车符(\r),下面的示例就应该有效。在
我也遇到了同样的问题。在
尝试这样做:
我刚刚删除了查询的
$regex
部分。在背景
我尝试做
{item["type"]: {"$not": item['name']}}
,pymongo返回了一个$not needs a regex or a document
错误。在所以,我尝试了:
{item["type"]: {"$not": {"$regex": item['name']}}}
,pymongo返回了一个$not cannot have a regex
错误。在我发现这是如此https://stackoverflow.com/a/20175230/9069964而这是最终对我有用的:
^{pr2}$我不得不放弃“$regex”部分,把“$not”我的regex东西给了。在
在这里,我们也许可以不使用}后跟一个空格,
$not
特性来解决这个问题。例如,如果我们不想让bon souple
或{bon
后面跟着一个空格,我们可以使用类似于的表达式:DEMO
我不太确定我们希望在这里提取什么,但我只是猜测,也许我们应该刷一下
bon
值,而不是后面跟空格,在"
之间。在此外,我们可能希望查看正则表达式查询要求,并根据需要调整表达式,例如使用转义或使用捕获组:
^{pr2}$或者:
或者:
或者:
DEMO
正则表达式电路
jex.im可视化正则表达式:
我不太确定这是我们想要的还是相关的,但是根据这个documentation,我们可以尝试使用:
或者:
在数据库.集合.查找
或者:
参考文献:
PyMongo $in + $regex
Performing regex Queries with pymongo
相关问题 更多 >
编程相关推荐