如果在Symfony- MongoDB-ODM中数据为空,则在odm查询(游标)上执行count()不会返回“0”
问题描述:
Performing count()
on odm query (cursor) does not return "0" if data is empty in Symfony- MongoDB-ODM
$query = $this->dm->createQueryBuilder('AppBundle:DocumentName');
$count = $query->getQuery()->count();
The var $count
always returns value greater than zero ("0"). Even if there is no data in document
Note : Converting cursor to arrays consumes more memory, Please Excuse this method.
答
You should do:
$count = $query->getQuery()->getSingleScalarResult();
Regards
答
you can use AggregationBuilder. Try this code in your documentNameRepository:
$qb = $this->createAggregationBuilder('Document\DocumentName');
$qb->count('nb_documents');
$results = $qb->execute();
return $results;
You can execute where operation before the count like below:
$qb->match()
->field('field_name')
->equals(10);
You can execute limit and skip operation before the count like below:
$qb->skip(10)
->limit(100);
You can read the documentation.