我可以在MongoDb的单个文档中将多个字段标记为@indexed吗?

时间:2020-06-21 10:17:31

标签: mongodb

在使用Spring Boot和MongoDb时,我在文档中使用 @indexed 注释。

我已经标记了名字用于索引。

我也可以将其他字段标记为索引吗? 该文件如下所述:

@Document
public class Person {
@Id private String id;
@Indexed(name = "first_name_index", direction = IndexDirection.DESCENDING)
private String firstName;
private String secondName;
private LocalDateTime dateOfBirth
}

将多个字段标记为索引是一种好习惯吗?

1 个答案:

答案 0 :(得分:1)

是的。如果查询是正交的,则可以将多个字段索引为@Indexed

  1. 您需要支持findByFirstNamefindByDateOfBirth查询。
  • 您将@Indexed注释添加到firstName
  • 您将@Indexed注释添加到dateOfBirth
  1. 您需要支持findByFirstNamefindByFirstNameAndDateOfBirth查询。
  • 您将@CompoundIndex(def = "{'findByFirstName': 1, 'dateOfBirth': 1}")添加到public class Person