Spring Data mongo - issue with Distinct collection

試著忘記壹切 提交于 2019-11-30 00:03:10

问题


Spring Data Mongo distinct doesn't works. I've following two documents.

/* 1 */
{
    "_id" : ObjectId("5ca746fd92bc0733a4a6633b"),
    "firstName" : "John",
    "lastName" : "Kerr",
    "emailId" : "john.kerr@gmail.com",
    "hobbies" : [ 
        {
            "interest" : "Indoor",
            "sports" : "Chess"
        }, 
        {
            "interest" : "Loveoor",
            "sports" : "Table Tennis"
        }
    ],
    "_class" : "com.example.Person"
}

/* 2 */
{
    "_id" : ObjectId("5ca746fd92bc0733a4a6633c"),
    "firstName" : "Neha",
    "lastName" : "Parate",
    "emailId" : "john.kerr@gmail.com",
    "hobbies" : [ 
        {
            "interest" : "Indoor",
            "sports" : "Chess"
        }, 
        {
            "interest" : "Loveoor",
            "sports" : "Table Tennis"
        }, 
        {
            "interest" : "Happydoor",
            "sports" : "Lawn Tennis"
        }
    ],
    "_class" : "com.example.Person"
}

When I do db.person.distinct('hobbies'), I get the distinct records easily.

[
    {
        "interest" : "Indoor",
        "sports" : "Chess"
    },
    {
        "interest" : "Loveoor",
        "sports" : "Table Tennis"
    },
    {
        "interest" : "Happydoor",
        "sports" : "Lawn Tennis"
    }
]

The same I wants to do using Spring Data Mongo or MongoTemplate. But none of the ways things are working.

@Query(value = "{}", fields = "{'hobbies' : 1}")
List<Person> findByDistinctHobbies();

回答1:


In the latest version of Spring Data Mongo as per docs: https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongo-template.query.distinct. You can even query to the embedded document to find out the distinct documents.

Through MongoTemplate you can achieve like below:

List<Object> object = mongoTemplate.query(Person.class).distinct("hobbies").all();
     for (Object object2 : object) {
       Hobbies hobbies = (Hobbies) object2;
       System.out.println(hobbies);
     }
}


来源:https://stackoverflow.com/questions/55535331/spring-data-mongo-issue-with-distinct-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!