我想从MongoDB集合中选择一个随机文档。如果我使用MySQL,我的解决方案将类似于this。如何随机选择Doctrine ODM?
如何使用Doctrine ODM查询构建器从MongoDB Collection中选择一个随机文档?
我想从MongoDB集合中选择一个随机文档。如果我使用MySQL,我的解决方案将类似于this。如何随机选择Doctrine ODM?
如何使用Doctrine ODM查询构建器从MongoDB Collection中选择一个随机文档?
我已经解决了我的问题是这样的:
public function getRandomUser()
{
$qb = $this->getDocumentManager()->createQueryBuilder('AppBundle:User');
$count = $qb->getQuery()->count();
$skip_count = random_int(0, $count);
$qb->skip($skip_count);
return $qb->getQuery()->getSingleResult();
}
<?php
// Create Query Builder.
$dm = $this->getDocumentManager()->createQueryBuilder('Document');
// Count documents.
$count = $dm->getQuery()->execute()->count();
// Get random number not exceeding $count variable.
$random = mt_rand(0, $count);
// Query for document with skip.
$random_document = $dm->skip($random)
->getQuery()
->getSingleResult();
尝试这种解决方案:
public function getRandomDocument()
{
$qb = $this->getDocumentManager()->createQueryBuilder('YourBundle:TargetDocument');
$count = $qb->getQuery()->count();
$skip_count = random_int(0, $count);
$qb->skip($skip_count);
return $qb->getQuery()->getSingleResult();
}