0 レビュー
2 回答
MongoDBのPHPのmysqli_num_rows()に相当するものは何ですか?
仕様
データベース: MongoDB 3.4
プログラミング言語: PHP 7.1
ライブラリ:MongoDBのPHPライブラリ1.2.0
サンプルコード
$result = $connection->db->collection->find($filter, $options);
MySQLでは、これを行います:
$number_of_rows = mysqli_num_rows($result);
物事を試したり調査したりするとき、私はこれを試しました:
$number_of_rows = $result->count();
レガシー( MongoDBドライバーには含まれていません)の一部であるため、このエラーが返されます:
Error: Call to undefined method MongoDB\Driver\Cursor::count()
count()またはsizeof()を使用しようとすると、結果は常に1になります。
$number_of_rows = count($result);
$number_of_rows = sizeof($result);
forループ内で$count変数を繰り返すことなく、このバージョン(または最新バージョン3.6)のMongoDBで適切に実行するにはどうすればよいですか?
同じ質問ですが、回答が古くなっていますここ。
わからない
0
レビュー
答え :
解決策:
これらの3つのオプションに対する@Yury-Fedorovの回答を拡張しました。私はこれをテストしました、そしてそれはあなたの側で働くはずです。
オプション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;
オプション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());
オプション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());
わからない
0
レビュー
答え :
解決策:
$result->count()
の代わりに$collection->count()
メソッドを使用できるはずです:
$query = []; // your criteria
$collection->count($query);
this のディスカッション、またはPHPの質問を含む別のMongoDBカウントに対する私のanswerをご覧ください。これはまったく同じではありません。
わからない
同様の質問
私たちのウェブサイトで同様の質問で答えを見つけてください。