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

时间:2019-04-27 16:45:25

标签: mongodb php-mongodb

以前,我是通过查询名称空间来检查集合是否存在的。

大致像这样,检查“ foo.bar”是否存在:

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

由于这仅适用于mmapv1,并且我已移至wiredTiger,因此我尝试依靠驱动程序抛出“ Database foo不存在”或“ Collection bar不存在”存在”。

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时错误消息已更改。

做到这一点的正确方法是与存储引擎无关的和将来的版本证明吗?

1 个答案:

答案 0 :(得分:0)

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