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?
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();
}
<?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();
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.
Firebase Cloud Functions: PubSub, "res.on is not a function"
TypeError: Cannot read properties of undefined (reading 'createMessageComponentCollector')
I have used TBS (TinyButStrong) for several PHP projects to generate DOCX or XLSX files based on a template
I am trying to configure nginx and have the following configuration in
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
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