Tips

Set timeouts for MongoDB queries

FIND:

1
2
3
4
5
6
7
8
9
10
$cursor = $this->getDocumentManager()
    ->createQueryBuilder()
    ...
    ->getQuery()
    ->getIterator()
    ->timeout(-1);
 
 <strong>foreach </strong>($cursor <strong>as </strong>$document) {
    ...
}

Timeout is not available in code completion, but does very well exist. Preferably, it is used for conversions or scripts that may run longer than 30 seconds and not for queries used on the front-end itself. 

COUNT:

1
2
3
4
5
6
7
$count = $this->getDocumentManager()
    ->createQueryBuilder()
    ...
    ->getQuery()
    ->getIterator()
    ->timeout(-1)
    ->count();

Don't use the getQuery for count, otherwise you will get a notification that the getIterator can't be invoked. You will need the getIterator to setup the timeout.

UPDATE / DELETE:

1
2
3
4
5
6
$cursor = $this->getDocumentManager()
    ->createQueryBuilder()
    ->update()
   ...
    ->getQuery([<strong>'timeout' </strong>=> -1])
    ->execute();
1
2
3
4
5
6
$cursor = $this->getDocumentManager()
    ->createQueryBuilder()
    ->remove()
    ...
    ->getQuery([<strong>'timeout' </strong>=> -1])
    ->execute();

Setting the timeout at -1 will disable the timeout, but you can also set another number.