Search code examples
mongodbphp-mongodb

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


Previously I was checking if a collection exists by querying the namespaces.

Roughly like this, to check if "foo.bar" exists:

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

As this only works with mmapv1 and I've moved to wiredTiger, I tried this instead relying on the driver throwing either "Database foo doesn't exist" or "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;
}

I don't want to list collections as there are thousands, but I don't like relying on the exception as I notice the error message changed when migrating from 3.6 to 4.0.

What is the proper way to do this that's storage engine agnostic and future version proof?


Solution

  • listCollections has a filter parameter that you can use to restrict the collections returned. It should end up looking something vaguely like db.runCommand({"listCollections": 1, filter: {name: "foo" }});