简体   繁体   中英

What is the equivalent of PHP's mysqli_num_rows() in MongoDB?

Specification

Database : MongoDB 3.4

Programming Language : PHP 7.1

Library : PHP library of MongoDB 1.2.0

Sample Code

$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.

Option 1

$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;

Option 2

$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());

Option 3

$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());

You should be able to use $collection->count() method instead of $result->count() :

$query = []; // your criteria
$collection->count($query);

Take a look at this discussion or at my answer to another MongoDB count with PHP question, which is not exactly the same is this one.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM