Skip to content
New issue

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

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Creating indexes #170

Closed
xplodwild opened this issue Dec 15, 2015 · 1 comment
Closed

Creating indexes #170

xplodwild opened this issue Dec 15, 2015 · 1 comment

Comments

@xplodwild
Copy link

Hello

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.

Thanks!

@bjori
Copy link
Contributor

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:

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

@bjori bjori closed this as completed Dec 15, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants