检查集合是否存在的正确方法是什么?

What's the correct way to check if a collection exists?

之前我通过查询命名空间来检查集合是否存在。

大致是这样,检查"foo.bar"是否存在:

return 1 === $client->selectCollection('foo','system.namespaces');
                    ->count(['name'=>'bar']);

因为这只适用于 mmapv1,而我已经转移到 wiredTiger,我尝试了这个而不是依赖驱动程序抛出 "Database foo doesn't exist" 或 "Collection bar doesn't exist"。

try {
  $command = new MongoDB\Driver\Command(['listIndexes'=>'bar']);
  $server->executeReadCommand('foo',$command);
  return true;
}
catch( MongoDB\Driver\Exception\CommandException $e ){
  return false;
}

我不想 列出 集合,因为集合有数千个,但我不喜欢依赖异常,因为我注意到从 3.6 迁移到时错误消息发生了变化4.0。

执行此存储引擎不可知且未来版本证明的正确方法是什么?

listCollections 有一个 filter 参数,您可以使用它来限制返回的集合。它最终应该看起来有点像 db.runCommand({"listCollections": 1, filter: {name: "foo" }});