问题
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