我在Perl中使用MongoDB工作。我有一个包含大文本字段的文档的集合,我需要能够在字段中找到包含多个字符串的所有行。
因此,例如,如果这是电影引号的数据库,则一行将具有值:
我们必须完全摧毁Arrakis的所有香料生产。公会和整个宇宙依赖于香料。能够摧毁一件东西的人控制着一件事。
我希望能够将该行与术语“spice”,“Arrakis”和“Guild”匹配,其中所有这些术语都必须在文本中。
如果提供的条款恰好是正确的顺序,我目前的方法只能达到匹配,即:
$db->get_collection( 'quotes' )->find( { quote => qr/spice.*Arrakis.*Guild/i } );
这是一场比赛,但是
$db->get_collection( 'quotes' )->find( { quote => qr/Guild.*spice.*Arrakis/i } );
不是匹配。
如果我正在使用SQL数据库,我可以这样做:
... WHERE quote LIKE '%spice%' and quote LIKE '%Arrakis%' and quote LIKE '%Guild%'
但是使用MongoDB接口,每个字段只能获得一次。
有没有办法匹配多个单词,在一个正则表达式中需要所有单词,或者是否有另一种方法可以在MongoDB接口中的字段中获得多个单独的裂缝?
一种方式:一堆积极的前瞻性断言:
#!/usr/bin/perl
use warnings;
use strict;
use feature qw/say/;
my @tests = ("The Guild demands that the spice must flow from Arrakis",
"House Atreides will be transported to Arrakis by the Guild.");
for my $test (@tests) {
if ($test =~ m/^(?=.*spice)
(?=.*Guild)
(?=.*Arrakis)/x) {
say "$test: matches";
} else {
say "$test: fails";
}
}
生产:
公会要求香料必须从Arrakis流出:匹配
公爵Leto将被公会运送到Arrakis:失败