Database : MongoDB 3.4
Programming Language : PHP 7.1
Library : PHP library of MongoDB 1.2.0
$result = $connection->db->collection->find($filter, $options);
In MySQL, you do this:
$number_of_rows = mysqli_num_rows($result);
When trying things out and doing some research, I've tried this:
$number_of_rows = $result->count();
It returns this error since it's part of the legacy (not included in the MongoDB driver ):
Error: Call to undefined method MongoDB\Driver\Cursor::count()
When I tried using count() or sizeof(), the result is always 1.
$number_of_rows = count($result);
$number_of_rows = sizeof($result);
How should it be done properly in this version (or the latest version 3.6) of MongoDB without having to iterate a $count variable inside a for-loop?
Same question but outdated answers here .
I expanded @Yury-Fedorov's answer to these 3 options. I have tested this and it should work on your end.
$filter = ['field' => 'value'];
$db = new \MongoDB\Driver\Manager('mongodb://localhost:27017');
$command = new \MongoDB\Driver\Command(['count' => $collection_name, 'query' => $filter]);
try {
$cursor = $db->executeCommand($database_name, $command);
} catch (\MongoDB\Driver\Exception\Exception $e) {
$error_message = $e->getMessage();
}
$count = $cursor->toArray()[0]->n;
$filter = ['field' => 'value'];
$options = ['option' => 'value'];
$db = new \MongoDB\Driver\Manager('mongodb://localhost:27017');
$query = new \MongoDB\Driver\Query($filter, $options);
try {
$cursor = $db->executeQuery("$database_name.$collection_name", $query);
} catch (\MongoDB\Driver\Exception\Exception $e) {
$error_message = $e->getMessage();
}
$count = count($cursor->toArray());
$filter = ['field' => 'value'];
$options = ['option' => 'value'];
$db = new \MongoDB\Client ('mongodb://localhost:27017');
try {
$cursor = $db->{$database_name}->{$collection_name}->find($filter, $options);
} catch (\MongoDB\Driver\Exception\Exception $e) {
$error_message = $e->getMessage();
}
$count = count($cursor->toArray());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.