How to select randomly with Doctrine ODM?

635
December 28, 2016, at 09:05 AM

I want to select one random document from MongoDB collection. If I'd used MySQL, my solution would be similar to this.

How can I select a random document from MongoDB Collection using Doctrine ODM query builder?

Answer 1

Try this solution:

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();
}
Answer 2
<?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();
Answer 3

I'd do it like this:

Get a random id from your entities count, generate a random number based on the count, this will be the position of the entity to pick, something like this:

$count = 'SELECT COUNT(ID) FROM [your table]';
$random_position = rand(0, $count);
//select entity based on the id generated of your entity
//get your entity manager $em
$query = $em->createQuery("SELECT e FROM Project\Entity e");
$query->setFirstResult($random_position)->setMaxResult(1);
$entity = $query->getResult();

This should give you an starting point.

Rent Charter Buses Company
READ ALSO
Using TinyButStrong (TBS) to generate a PDF from a DOCX

Using TinyButStrong (TBS) to generate a PDF from a DOCX

I have used TBS (TinyButStrong) for several PHP projects to generate DOCX or XLSX files based on a template

639
NGINX server configuration

NGINX server configuration

I am trying to configure nginx and have the following configuration in

547
For loop doesn&#39;t regen random string, stays the same

For loop doesn't regen random string, stays the same

So I m trying to get a random string generator to work with a for loopI have gotten it to loop the number of times it should but it refuses to generate a new string per loop

327
Form plugin for WordPress that can create horizontal radio button options

Form plugin for WordPress that can create horizontal radio button options

I am currently working on creating multiple forms for a WordPress website (35 unique ones) and they will all be very similar-lookingI would really appreciate any tips on how to do this effectively with templates

302