pazulx
pazulx

Reputation: 2379

Symfony2 app, MongoDB: Count all records matching criteria

In my controller I'm fetching limited number of objects (for pagination) like this:

    $dm   = $this->get('doctrine_mongodb');
    $repo = $dm->getRepository('AcmeMyBundle:MyDocument');

    $criteria = array(
        'field1'    => 'value1',
        'field1'    => 'value1',
    );

    $logs = $repo->findBy(
        $criteria,                      /* criteria */
        array($field => $direction),    /* sort */
        $limit,                         /* limit */
        (($page-1)*$limit)?:null        /* skip */
    );

Now I like to get total number of records that meet the $criteria.

I was trying to count it like this:

$count = $repo->createQueryBuilder('MyDocument')
    ->count()->getQuery()->execute();

But it counts all records in collection. How can I apply $criteria to that counting query?

I need result as native MongoDB db.MyDocument.find({'field2': "value1", 'field2': "value2"}).count()

Upvotes: 0

Views: 1632

Answers (1)

pazulx
pazulx

Reputation: 2379

Done it like this:

    $countQuery = $repo
        ->createQueryBuilder('MyDocument')
        ->requireIndexes(false)
        ;

    foreach(array_filter($criteria) as $field=>$value){
        $countQuery->field($field)->equals($value);
    }

    $count = $countQuery->count()->getQuery()->execute();

Upvotes: 1

Related Questions