Lal Mohan
Lal Mohan

Reputation: 323

How to query mongodb with condition “like” in symfony2

I need to search the users in my symfony2 app

If a user enter an alphabet in search box and submit then he need to get the users starting with that alphabet.

How to achieve this? Below code will get the exact user that we type in textbox.

How to apply "like" query in this

my action code

public function searchAction(Request $request)
{

    $fname = $request->query->get('fname');
    if(isset($fname)){
    $user = $this->get('doctrine.odm.mongodb.document_manager')
        ->getRepository('WishbotWebBundle:User')
        ->findByusername($fname);
         return $this->render('WishbotWebBundle:Default:search.html.twig',array('user'=>$user));

    }else{
        return $this->render('WishbotWebBundle:Default:search.html.twig');

    }
}

Upvotes: 2

Views: 2096

Answers (1)

Sgoettschkes
Sgoettschkes

Reputation: 13189

First of all, let's look at MongoDB: Searching with regex can be done by defining a regex, as explained here:

db.users.find({"username": /^a/})

The same can be done in php by defining a regex, explained here:

$collection->find(array('name'=> array('$regex' => '^a'));

You can use the almost exact same regex syntax with the Doctrine MongoDB ODM:

$user = $this->get('doctrine.odm.mongodb.document_manager')
        ->getRepository('WishbotWebBundle:User')
        ->findByUsername(array('$regex' => $fname));

Please note that a collection of documents is returned, even if only one is found. The regex above also matches all documents where the username contains the $fname string anywhere.

If you want usernames which start with the $fname, you need to use '^' . $fname.

Upvotes: 2

Related Questions