mongodbsymfonydoctrine-odm

Full text search in mongodb in Symfony 3.4


I'm trying to use full text search in mongodb:

db.Product.createIndex({"name": "text"})
db.Product.find({$text: {$search: "xxxxx"}})

how to use this in controller to symfony?


Solution

  • Thank you for all the answers. In summary, the controller for the search engine looks like the following:

    class SearchController extends Controller
    {
      public function searchBarAction()
      {
        $form = $this->createFormBuilder(null)
            ->setMethod('GET')
            ->add('search', TextType::class)
            ->getForm();
    
        return $this->render('AppBundle:Components:_searchBar.html.twig', [
            'form' => $form->createView()
        ]);
     }
    
    /**
     * @param Request $request
     */
    public function handleSearchAction(Request $request)
    {
    
        $searchData = $request->query->get('form')['search'];
    
    
        $dbName = 'ece';
        $connection = $this->container->get('doctrine_mongodb')->getConnection();
        $mongo = $connection->getMongo();
        $db = $mongo->selectDB($dbName);
    
        $resultSetProduct = $db->Product->find([
            '$text' => ['$search' => $searchData]
        ]);
    
        $resultSet = $db->MainData->find([
            '$text' => ['$search' => $searchData]
        ]);
    
        $itemProduct =  $resultSetProduct->count();
        $itemSet = $resultSet->count() + $itemProduct;
    
    
        return $this->render('search/index.html.twig', [
            'searchData' => $searchData,
            'resultSetProduct' => $resultSetProduct,
            'itemProduct' => $itemProduct,
            'itemSet' => $itemSet,
            'resultSet' => $resultSet
    
        ]);
     }
    }