简体   繁体   English

带有排序的 MongoDB 复合索引前缀

[英]MongoDB Compound Index Prefix with Sort

I have trouble deciding where to best put sorting field in a mongodb compound index.我无法决定将排序字段放在 mongodb 复合索引中的最佳位置。

My understanding is that we need to choose the highest cardinality & selectivity as the preceeding fields in a compound index我的理解是我们需要选择最高基数和选择性作为复合索引中的前导字段

db.person.createIndex({ rating: 1, name: 1, gender: 1});

For this example, rating only ranges from 1 to 5 and gender is M or F So, name is always the highest cardinality & selectivity and should be the leftmost field in the compound index;对于这个例子,评分范围只有 1 到 5,性别是 M 或 F 所以,名字总是最高的基数和选择性,应该是复合索引中最左边的字段; however, the use case for query is such that rating is always provided in the query, and either name or gender can optionally be provided via filter in the application.但是,查询的用例是在查询中始终提供评级,并且可以通过应用程序中的过滤器选择性地提供姓名或性别。

Which option is best for this case:哪个选项最适合这种情况:

1) 1)

db.person.createIndex({ rating: 1, name: 1, gender: 1});

2) 2)

db.person.createIndex({ rating: 1});
db.person.createIndex({ name: 1, gender: 1});
db.person.createIndex({ gender: 1});

You need to add these indexes:您需要添加这些索引:

// supports query with rating and gender specified
db.person.createIndex({ rating: 1, gender: 1});

// supports query with rating and name (and optionally gender) specified
db.person.createIndex({ name: 1, rating: 1, gender: 1});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM