【发布时间】:2014-10-29 22:07:28
【问题描述】:
我需要在集合中找到一个或多个在其 _id 字段中具有特定字符串的文档。
这被证明是一个问题,因为 _id 字段是一个对象而不是字符串,所以我不能只是对其进行正则表达式。
例如,假设我有这些带有这些 _id 的文档:
54060b811e8e813c55000058
54060e9e1e8e813c55000059
540738e082fa085e5f000015
我想搜索“00005”,那么结果应该是
54060b811e8e813c55000058
54060e9e1e8e813c55000059
有没有办法做到这一点?
我需要一个 jquery 数据表实现,它使用 php 进行服务器端处理。
这意味着我需要在这部分代码中添加一些内容:
if ( !empty($input['sSearch']) ) {
$sSearch = $input['sSearch'];
for ( $i=0 ; $i < $iColumns ; $i++ ) {
if ($input['bSearchable_'.$i] == 'true') {
if ($input['bRegex'] == 'true') {
$sRegex = str_replace('/', '\/', $sSearch);
} else {
$sRegex = preg_quote($sSearch, '/');
}
$searchTermsAny[] = array(
$dataProps[$i] => new MongoRegex( '/'.$sRegex.'/i' )
);
}
}
}
任何建议都会被采纳
更新:
感谢 saj,似乎可以通过使用类似这样的 $where 子句来使用部分 _id 查找项目:
$where: "this._id.toString().match(/pattern/i)"
我尝试将它添加到这样的 php 代码中:
if ( !empty($input['sSearch']) ) {
$sSearch = $input['sSearch'];
for ( $i=0 ; $i < $iColumns ; $i++ ) {
if ($input['bSearchable_'.$i] == 'true') {
if ($input['bRegex'] == 'true') {
$sRegex = str_replace('/', '\/', $sSearch);
} else {
$sRegex = preg_quote($sSearch, '/');
}
$searchTermsAny[] = array(
$dataProps[$i] => new MongoRegex( '/'.$sRegex.'/i',
'$where: "this._id.toString().match(/'.$sRegex.'/i)"' )
);
}
}
}
但是现在每个查询都返回所有记录,而不是只返回应该匹配的记录。
有什么想法吗?
解决方案:
感谢您的帮助,我已经弄清楚了,为了在 _id 字段中添加开放式搜索,我需要在查询数组的 $or 部分中添加 $where 子句。
特别是在我的情况下,我使用了以下代码:
if ( !empty($input['sSearch']) ) {
$sSearch = $input['sSearch'];
for ( $i=0 ; $i < $iColumns ; $i++ ) {
if ($input['bSearchable_'.$i] == 'true') {
if ($input['bRegex'] == 'true') {
$sRegex = str_replace('/', '\/', $sSearch);
} else {
$sRegex = preg_quote($sSearch, '/');
}
$searchTermsAny[] = array(
$dataProps[$i] => new MongoRegex( '/'.$sRegex.'/i')
);
}
}
// add this line for string search inside the _id field
$searchTermsAny[]['$where'] = "this._id.str.match(/$sSearch/)";
}
谢谢你的帮助:)
就性能而言,我同意这是错误的方法,我将确保添加一个带有 _id 的字符串字段,以提高性能,但至少现在我有一个可行的解决方案.
【问题讨论】:
-
它可能不知道 php 抱歉,这里是 Java 版本的链接jira.mongodb.org/browse/SERVER-1146
-
这似乎是要走的路,但我在实施它时遇到了麻烦,我会更新我的问题,也许之前有人已经这样做了
标签: php regex mongodb datatables