MongoRepository 在数组中查找列表

MongoRepository Find List in Array

我有一个 document 看起来像这样

@Document
public @Data class Note {

    @Id
    private String noteId;
    private String owner;
    @TextIndexed
    private String name;
    @TextIndexed
    private String text;
    private List<String> tags;
    private LocalDate date;
}

我还使用 spring data mongodbmongodb 数据存储上进行操作。 我创建了接口

public interface NoteRepository extends MongoRepository<Note, String> {
    List<Note> findByTags(List<String> tags);
}

我存储的对象是这样的

[
    {
        "noteId": "594e4adc3bc5152218f933b4",
        "owner": "system",
        "name": "simple note",
        "text": "My text",
        "tags": [
            "tag1",
            "tag2",
            "tag3"
        ],
        "date": [
            1992,
            12,
            15
        ]
    }
]

但除非我不向 findByTags 方法提供 tag1, tag2, tag3 等标签列表,否则不会 return 任何结果。例如tag1, tag2 return什么都没有等等等等

我应该如何对这些标签进行搜索?使用一些 TextCriteria?

这取决于你想提供什么。

如果您只需要一个值,那么 MongoDB 不关心数据是否在数组中,只会在所有条目中查找匹配项

public interface NoteRepository extends MongoRepository<Note, String> {
    List<Note> findByTags(String tags);
}

如果你想要一个可变大小的列表来比较可能匹配的"any",那么有一个keyword used by spring-mongo that effects the $in操作:

public interface NoteRepository extends MongoRepository<Note, String> {
    List<Note> findByTagsIn(List<String> tags);
}

所以第一个是您只想 "tag1" 匹配数据的地方。第二个将匹配 List,如 "tag1", "tag2",或任何只要 'at least one' 实际存在于被搜索数组中的任何东西。