0

Solved. Just change db.test.ensureIndex(['name']) => to db.test.ensureIndex({'name':1});


I was testing MongoDB today. I have test collection with 100 000 documents. Each document has such structure {_id:123123, name: 'foo123123'}

Test code written in PHP

set_time_limit(0);
ini_set('display_errors', 1);

$mongo = new Mongo("mongodb://127.0.0.1:27017");
$db = $mongo->test;
$collection = $db->test;

$start = microtime(true);

for($i=0; $i<10000; $i++){
    $obj = $collection->findOne(array('name'=>'foo'.$i));
}

$end = microtime(true);
var_dump($end-$start);

First test without index on name field is 21 seconds Than I add index

db.test.ensureIndex(['name']);

db.test.getIndexes(); [ { "v" : 1, "key" : { "_id" : 1 }, "ns" : "test.test", "name" : "id" }, { "v" : 1, "key" : [ "name" ], "ns" : "test.test", "name" : "0_" } ]

And repeat test. And got 21 seonds again. Why mongo doesn't use index in my case?

1 Answer 1

2

You should use the explain method to view the execution plan and find out whether or not it is using the index correctly.

http://www.mongodb.org/display/DOCS/Explain

I also think that you want to update your index creation command to this:

db.things.ensureIndex({"name": 1})

It isn't an array, but rather a key-value pair where the key is the property you want to index and the value is 1 or -1 depending on whether you want it to be indexed ascending or descending.

Check the docs for indexes: http://www.mongodb.org/display/DOCS/Indexes#Indexes-CreationOptions

Sign up to request clarification or add additional context in comments.

7 Comments

For my query it is { "cursor" : "BasicCursor", "nscanned" : 100000, "nscannedObjects" : 100000, "n" : 1, "millis" : 68, "nYields" : 0, "nChunkSkips" : 0, "isMultiKey" : false, "indexOnly" : false, "indexBounds" : { } }
So then youre correct that it is not using an index - if it were, it would say that the cursor were a B-Tree Index rather than a basic cursor.
I've updated my answer with more information about indexes - please have a look
Don't you know why it happens?
Thanks! You are right. I change my command to db.things.ensureIndex({"name": 1}) and now it is using index
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.