Minal Shah
Minal Shah

Reputation: 1486

Can I mark more than one field as @indexed in single document in MongoDb?

I am using @indexed annotation in my document for the person while using spring boot and MongoDb.

I have already marked firstName to be used for indexing.

Can I mark other fields as well for index? The document is as mentioned below:

@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
}

Is it a good practice to mark more than one field as indexed?

Upvotes: 0

Views: 115

Answers (1)

Yes. You can index multiple fields as @Indexed if your queries are orthogonal.

  1. You need to support findByFirstName and findByDateOfBirth queries.
  • you add @Indexed annotation to firstName
  • you add @Indexed annotation to dateOfBirth
  1. You need to support findByFirstName and findByFirstNameAndDateOfBirth queries.
  • you add @CompoundIndex(def = "{'findByFirstName': 1, 'dateOfBirth': 1}") to public class Person.

Upvotes: 1

Related Questions