Q: Get distinct names of objects from a lists defined inside the mongodb documents I work with Spring Boot and MongoDB. I am looking for a solution to get a list of distinct hobbies names. Additionally all of the hobbies have to have requested group. The problem is that hobbies are defined inside the person document.
@Document("persons")
@Data
class Person {
    @Id
    private String personId;
    private String name;
    private List<Hobby> hobbies;
}

@Data
class Hobby {
    private String name;
    private String description;
    private String hobbyGroup;
}

Example
Person documents from the database
{
    "_id" : ObjectId("id1"),
    "name" : "some person",
    "hobbies" : [
        {
            "name" : "A",
            "description" : "description1",
            "hobbyGroup" : "group1"
        },
        {
            "name" : "AB",
            "description" : "description2",
            "hobbyGroup" : "group1"
        }
    ]
},
{
    "_id" : ObjectId("id2"),
    "name" : "some person 2",
    "hobbies" : [
        {
            "name" : "A",
            "description" : "description 3",
            "hobbyGroup" : "group1"
        },
        {
            "name" : "ABC",
            "description" : "description 4",
            "hobbyGroup" : "group1"
        },
        {
            "name" : "other group hobby",
            "description" : "description 5",
            "hobbyGroup" : "group2"
        }
    ]
}

In this scenario I want to get a list of all distinct hobbies names with hobbyGroup group1. The result should look like: ["A", "AB", "ABC"]
I tried something like this method below but I get all of the names and combined per person : ["A,AB", "A,ABC,other group hobby"]
@Repository
interface PersonRepository extends MongoRepository<Person, String> {
    @Aggregation(pipeline = {
            "{'$match': {'hobbies.hobbyGroup': :#{#hobbyGroup}}}",
            "{'$group': {'_id': '$hobbies.name'}}"
    })
    List<String> findAllDistinctHobbiesNames(@Param("hobbyGroup") String hobbyGroup);
}

Thanks in advance for help.

A: Try unwinding the hobbies array, and then try:
db.collection.aggregate([
  {
    "$unwind": "$hobbies"
  },
  {
    "$match": {
      "hobbies.hobbyGroup": "group1"
    }
  },
  {
    "$group": {
      "_id": "$hobbies.name",
    }
  }
])

Playground link.
