I have documents with “tags” arrays as properties. Now I want to query all distinct tag-items.
{ "name": "test1", "tags": ["tag1","tag2", "tag3"] }, { "name": "test2", "tags": ["tag1"] }
Solution in mongo shell:
db.ApiModel.distinct("tags")
which gives me:
["tag1", "tag2", "tag3"]
But how can I achieve the same result with Panache? The PanacheMongoEntity does not offer a specific distinct method. Nor do i know how to use the find
method to achieve my goal or if it even is possible using this method.
All I could possibly think of is finding all tags with find("tags", "*")
(is * the wildcard?) and then dealing with duplicates in Java, but I don’t believe that’s the intended use.
Advertisement
Answer
You can use either of the two methods to get distinct tags
from the collection test
.
public List<String> getDistinctTags() { return Tags .<Tags>mongoCollection() .distinct("tags", String.class) .into(new ArrayList<String>()); } public List<String> getDistinctTags() { return Tags .<Tags>streamAll() .flatMap(e -> e.tags.stream()) .distinct() .collect(toList()); }
Assuming the Tags
class is defined as follows and represents the Panache entity:
@MongoEntity(collection="test") public class Tags extends PanacheMongoEntity { public String name; public List<String> tags; // ... }