PHP MongoDB - Use of the aggregate command without the cursor option is deprecated. What?

When you query something to MongoDB and you expect results, you will have this variable called cursor, which simply is a pointer to the document you currently did read. It is just like a scrollbar in the browser.

You can specify how many documents it should read into a buffer batchSize as you did with value 1.

It is useful when you know how much documents you expect to read. When you only need 10 documents, you can get all those in a single network packet using batchSize => 10. When specify batchSize => 5, it will take longer because it does take two network packets to the database to get the expected 10 documents.

You are safe using the default batchSize.

You can try to iterate over the cursor using foreach like in an example in the docs: http://php.net/manual/en/class.mongocommandcursor.php

Im not sure if the php.net documentation is up to date with the most current version of the MongoDB driver.


From the latest MongoDB manual the aggregate operation have changed.

aggregate without cursor

MongoDB 3.4 deprecates the use of aggregate command without the cursor option, unless the pipeline includes the explain option. When returning aggregation results inline using the aggregate command, specify the cursor option using the default batch size cursor: {} or specify the batch size in the cursor option cursor: { batchSize: }.

You can just specify that parameter for your function call with adding [ "cursor" => [ "batchSize" => 0 ] ] as the second parameter will solve this. refer here.

You can also refer to this SO question for the cursor parameter usage.


You have to use aggregateCursor which returns the cursor row instead of results only.

Something like

The first batch is by default set at 101 results.

$cur = $this->db->{$collection}->aggregateCursor($pipeline);

Set the batchsize ( the second parameter from your question ) on aggregate cursor of 50 for subsequent batches. If you don't use below option the default will fetch around 4 MB.

$cur->batchSize( 50 );

You can now iterate and read results to get all documents.

The server will fetch initial(first) batch of 101 documents on first loop iteration followed by subsequent batch at 102 iteration and at intervals of 50 on rest of batches until you exhaust the cursor.

foreach ( $cur as $result )
{
   echo $result['_id'], "\n";
}

To control batch size for first batch, you can specify batchSize as cursor option but generally it is not needed.

$cur = $this->db->{$collection}->aggregateCursor($pipeline, 'cursor' => [ 'batchSize' => 1 ]);

Reference: https://derickrethans.nl/aggregation-cursor.html