Spring MongoDB - Difference between @Indexed and @Field annotations

fireball.1 :

I am trying to understand how the two different annotations of @Indexed and @Field differ while defining a model in Java Spring Boot.

public class Notation {
    @Id
    private String id;

    @Field("value")
    private String value;

    @Field("description")
    private String description;

    @Field("frequency")
    private int frequency;
}
public class Notation {
    @Id
    private String id;

    @Indexed("value")
    private String value;

    @Indexed("description")
    private String description;

    @Field("frequency")
    private int frequency;
}

My use case is to finally implement a search from the repository based on both value and description fields, so it would be good to get an idea of how the data is structured in the two and what are the various options one can use from these annotations.

Rajat Goel :

@Indexed annotation is will add an index that on that field in your mongo server. It takes an optional string parameter, which will be the index name and nothing to do with the field name. You should have only those fields indexed which will be used for filtering out documents.

@Field is used if you want to have different names in your java code and MongoDB collection.

For eg.

@Field("desc")
private String description;

In this case, in your MongoDB collection, you will find field name as "desc" while in your java code you will be referencing it as "description"

@Field("description")
private String description;

In the above case, there is no need for using @Field annotation

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=154833&siteId=1