MongoDB: two field index and document field index

I need to index the collection by two fields (unique index) like field1 and field2. What is the best approach in terms of performance:

  • Create a regular two-column index

    -or -

  • Combine these two fields in one document field {field1: value, field2: value2} and index this field?

Note. I will always request these two fields together.

+6
source share
2 answers

You can split the columns and create a single index that will increase performance while querying both fields at the same time.

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

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

Having columns in one column does not increase performance 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 whole document

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

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

It may be possible to increase productivity, but, doubtfully, a lot. Use a test database, create test data, and compare some tests to figure it out. We would love to hear your results.

+3
source

I would create a composite index for both fields. This will take up less disk space because you will not need to store an extra combo box and provide you with an extra extra index over the first box, i.e. The index over { a:1, b:1 } also the index over { a:1 } .

+1
source

Source: https://habr.com/ru/post/888474/


All Articles