dshapiro
dshapiro

Reputation: 1107

How can I verify that a mongo index is working properly?

I've got a small collection of mp3s in a mongo 2.6 DB. A document from this "songs" collection might look like this:

{_id: ..., name: "shagCarpet.mp3", tags: ["acapella", "rap"]}

I expect this collection to grow rapidly in the near future, so I want to index this collection for easy searching. I created a multi-key index on the "tags" field like so:

db.songs.createIndex({"tags": 1})

Since the collection is currently small, I don't see a performance gain by adding the index. How can I verify that the index is working properly? Can I look at the data in the index? I'm aware of db.songs.getIndexes(), but that only regurgitates what I told Mongo when I created the index. I'd like to actually see what the index data looks like.

Upvotes: 2

Views: 2867

Answers (3)

Ali80
Ali80

Reputation: 8676

use

db.songs.find({"tags":"accapella"}).explain("executionStats");

if nReturned equals docsExamined, it means that no unnecessary documents where examined and your index covers your query completely.

also here is a good article https://www.percona.com/blog/2018/09/06/mongodb-investigate-queries-with-explain-index-usage-part-2/

Upvotes: 0

Alan Bogu
Alan Bogu

Reputation: 775

you will get more info by using explain():

db.songs.find({"tags":"accapella"}).explain();

But I presume you wanna compare the speed of the query that is using the index with the speed of a normal collection scan(no index). You can force query to do a collection scan by using hint() method ie. on _id.

db.songs.find({"tags":"accapella"}).hint({_id:1}).explain();

Then compare explain() "millis" property between the two - you should see that the query without hint({_id:1}) is faster.

Upvotes: 2

The first step to determining if your indexes are working correctly is determining how you are going to be searching your database. Once you find the queries that will be run most frequently and/or will be most expensive, run them in the shell and append the .explain() call. For example:

db.songs.find(...).explain();

This will dump a lot of info out, part of which will tell you if an index was used, and if so which ones and in what order. For details of what it all means, see here.

Upvotes: 2

Related Questions