Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Already on GitHub? Sign in to your account

Creating indexes #170

xplodwild opened this Issue Dec 15, 2015 · 1 comment


None yet
2 participants


I couldn't find any example using the new MongoDB Driver (using it in PHP7 fwiw) on how to run commands such as createIndex/ensureIndex on a collection?

I tried using the executeCommand method, but it seems like it's intended only for management/administration commands, and not collection methods.



bjori commented Dec 15, 2015

Keep in mind that the raw driver is not meant to be used directly.
The main gateway should be the https://github.com/mongodb/mongo-php-library which contains helper methods for this sort of functionality.

Using the raw driver requires extensive knowledge of inner workings of MongoDB, and all its internal commands -- such as how to create an index.

To get you quickly running, here is how it works in MongoDB 2.6 and later:

$manager = new MongoDB\Driver\Manager("mongodb://");
$command = new MongoDB\Driver\Command([
    "createIndexes" => "collectionName",
    "indexes"       => [[
        "name" => "indexName",
        "key"  => [ "keyName" => 1],
        "ns"   => "databaseName.collectionName",
$result = $manager->executeCommand("databaseName", $command);

@bjori bjori closed this Dec 15, 2015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment