MongoDB ODM SELECT COUNT(*) equivalent

chris picture chris · Jun 11, 2012 · Viewed 12.8k times · Source

I wonder if there is an equivalent to the MySQL-Query:

   SELECT COUNT(*) FROM users

in MongoDB ODM?

This might work:

$qb = $this->dm->createQueryBuilder('Documents\Functional\Users');
$qb->select('id');   
$query   = $qb->getQuery();
$results = $query->execute();
echo $query->count(); 

But aren't then all IDs returned and how does this affect performance if there are more complex documents in database. I don't want too send to much data around just to get a count.

Answer

Diego Vidal picture Diego Vidal · Dec 14, 2013

A small contribution:

if you run the count this way:

$count = $this->dm->createQueryBuilder('Documents\Functional\Users')
         ->getQuery()->execute()->count();

Doctrine runs this query:

db.collection.find();

however, if the code is as follows:

$count = $this->dm->createQueryBuilder('Documents\Functional\Users')
         ->count()->getQuery()->execute();

Doctrine in this case run this query:

db.collection.count();

I do not know if there is improvement in performance, but I think most optimal

I hope that is helpful