我想从 mongodb 集合中选择一个随机文档。如果我使用MySQL,我的解决方案将与此相似。
如何使用 Doctrine ODM 查询构建器从MongoDB收藏中选择随机文档?
我以这种方式解决了我的问题:
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();
由于您的Mongo服务器为3.2或更高版
$ab = $this->dm->createAggregationBuilder(User::class);
$ab->sample($count);
return $ab->hydrate(User::class)->execute();
请记住,结果集可以包含独特的元素,额外阅读$ sample https://docs.mongodb.com/manual/reference/reference/operator/aggregation/aggregation/sample/#behavior
对于旧的mongo服务器,您应该在持久并使用$ lt- $ gt查询随机集时为每个文档设置随机值,请参阅MongoDB
尝试以下解决方案:
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();
}