Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: Two-field index vs document field index

I need to index a collection by two fields (unique index), say field1 and field2. What's better approach in terms of performance:

  1. Create a regular two-column index

    -or -

  2. Combine those two fields in a single document field {field1 : value, field2 : value2} and index that field?

Note: I will always be querying by those two fields together.

like image 636
Andrey Avatar asked May 18 '11 21:05

Andrey


2 Answers

You can keep the columns separate and create a single index that will increase performance when querying both fields together.

db.things.ensureIndex({field1:1, field2:1});

http://www.mongodb.org/display/DOCS/Indexes#Indexes-CompoundKeysIndexes

Having the columns in the same column provides no performance increases, because you must index them the same way:

db.things.ensureIndex({fields.field1:1, fields.field2:1});

http://www.mongodb.org/display/DOCS/Indexes#Indexes-EmbeddedKeys

Or you can index the entire document

db.things.ensureIndex({fields: 1});

http://www.mongodb.org/display/DOCS/Indexes#Indexes-DocumentsasKeys

There could be a possible performance increase, but doubtfully very much. Use the test database, create test data and benchmark some tests to figure it out. We would love to hear your results.

like image 56
Bryan Avatar answered Nov 10 '22 01:11

Bryan


I'd create a compound index over both fields. This'll take up less disk space because you won't need to store the extra combined field, and give you the bonus of an additional index over the first field, i.e. an index over { a:1, b:1 } is also an index over { a:1 }.

like image 26
Chris Fulstow Avatar answered Nov 10 '22 01:11

Chris Fulstow