Search code examples
mongodbsymfonydoctrine-ormsymfony-2.1doctrine-odm

How to create a WHERE ... OR ... query with MongoDB in Symfony2?


Inside my UserRepository I want to create custom queries, like the ones I can create with $dm->createQuery('some query') when not using MongoDB.

How can I do this? I see that $this->createQueryBuilder() method exists, but $this->createQuery() does not.

I also tried this as it would make sense, but didn't work:

$this->createQueryBuilder('u')
    ->where(array('$or' => array(
        array('u.username' => $username),
        array('u.email' => $username)
    )))
    // ...

It says that $or is an invalid operator.


Solution

  • Found it here: Doctrine2 Mongodb adding more $or operator

    /**
     * Adds an "or" expression to the current query.
     *
     * You can create the expression using the expr() method:
     *
     *     $qb = $this->createQueryBuilder('User');
     *     $qb
     *         ->addOr($qb->expr()->field('first_name')->equals('Kris'))
     *         ->addOr($qb->expr()->field('first_name')->equals('Chris'));
     *
     * @param array|QueryBuilder $expression
     * @return Builder
     */
    
    
    
    /**
     * Adds an "and" expression to the current query.
     *
     * You can create the expression using the expr() method:
     *
     *     $qb = $this->createQueryBuilder('User');
     *     $qb
     *         ->addAnd($qb->expr()->field('first_name')->equals('Kris'))
     *         ->addAnd($qb->expr()->field('first_name')->equals('Chris'));
     *
     * @param array|QueryBuilder $expression
     * @return Query
     */