php mongodb'$ or'正则表达式搜索 [英] php mongodb '$or' regex search

查看:199
本文介绍了php mongodb'$ or'正则表达式搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试查询mongodb视频"集合以按标题"或标签"字段查找结果...即使我搜索标题和/或标签中的术语,它仍会返回0个结果...任何帮助将不胜感激

i'm trying to query mongodb "videos" collection to find results by "title" or "tags" fields... it keeps returning 0 results even when i search for terms i know are in the title and/or tags... any help would be appreciated

<?php
$user_query = preg_replace("/[[:blank:]]+/"," ", $_GET['q']);
$arr_query = explode(' ', $user_query);

foreach ($arr_query as $q) {
    $title[] = '/'. $q .'/i';
    $tags[] = '/'. $q .'/i';
}
$who=array(
   '$or' => array(
        array('$in' => array('$regex' => $title)),
        array('$in' => array('$regex' => $tags))
            )
    );

$vids=$videos->find($who);
?>

推荐答案

$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_GET['q']);
$search_string = $search_string;

    //Connecting mongoDB
    $dbhost = 'localhost';
    $dbname = 'yourdbname';
    $port = '27017';

    $m = new MongoClient();
    $db = $m->$dbname;

    if($m){
        // select a collection
        $videos = $db->videos;

        // search for title and tags 
        $searchQuery = array(
            '$or' => array(
                array(
                    'title' => array(
                        '$regex' => $search_string,
                        ),
                    ),
                array(
                    'tags' => array(
                        '$regex' => $search_string,
                        ),
                    ),
                )
            );

        $cursor = $videos->find($searchQuery);

        foreach ($cursor as $doc) {
            var_dump($doc);
            //or what ever you want
            //var_dump($doc['title']);
        }

    else{
       echo "Collection videos cant select :( <br>";die();
    }

认为这会有所帮助. :D

Thinks this will help. :D

这篇关于php mongodb'$ or'正则表达式搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆