I need to find either one or more documents in a collection that have a specific string in their _id field.
this is proving to be a problem since the _id field is an object and not a string so i cant just regex it.
for example lets say i have these documents with these _id:
54060b811e8e813c55000058
54060e9e1e8e813c55000059
540738e082fa085e5f000015
and i want to search for "00005" then the result should be
54060b811e8e813c55000058
54060e9e1e8e813c55000059
is there anyway to accomplish this?
i need this for a jquery datatables implementaion which uses the server-side processing with php.
this means i need to add something to this portion of the code:
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' )
);
}
}
}
any advice would be apriciated
UPDATE:
thanks to saj it seems it is possible to find items using a partial _id by using a $where clause something like this:
$where: "this._id.toString().match(/pattern/i)"
i tried adding this to the php code like this:
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)"' )
);
}
}
}
however now every query returns all records instead of only the ones that are suppsoed to match.
any ideas?
SOLUTION:
thanks to your help i have figured this out, in order to add an open search in the _id field i need to add a $where clause in the $or section of the query array.
specificaly in my situation i used the following code:
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/)";
}
thank you for your help :)
as far as performance i agree this is the WRONG way to go and i will make sure to have an added strign field with the _id in it to make performance much better, but for now atleast i have a working solution to the problem.