1

Can MongoDB create compound indexes using continuous numeric fields as the prefix?

For example:

db.col.createIndex({height_to_weight_ratio: 1, income_to_expense_ratio: 1})

As I understand it, a compound index works with categorical data because for each categorical value in the prefix there are multiple values in the suffix fields that fall under that category.

If a real number is to serve as the prefix, then the field that follows may only have one or a few values that fall under this real number. So I don't understand how a compound index can be constructed if the prefix is a field that holds continuous real numbers.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

1

Yes, MongoDB can create a compound index that starts with a real or decimal value.

While querying, it can still scan the index for values that satisfy the filter, even if they are all unique.

The leading values being unique will impact the amount of space needed to store the index. MongoDB stores indexes using prefix compression. The index entries consist of the value of each indexed fields concatenated with a separator. When adjacent index entries in a page of the index contain common bytes at the start, the second entry will replace them with a tag indicating the number of omitted bytes, reducing storage.

Note that even with unique floats, once they are sorted numerically it is quite possible that at least the sign bit and exponent would be the same between adjacent values, so they may also see some space savings from prefix compression.

Joe
  • 25,000
  • 3
  • 22
  • 44