Spring Data Mongo distinct不起作用。我跟着两份文件。
/* 1 */
{
"_id" : ObjectId("5ca746fd92bc0733a4a6633b"),
"firstName" : "John",
"lastName" : "Kerr",
"emailId" : "[email protected]",
"hobbies" : [
{
"interest" : "Indoor",
"sports" : "Chess"
},
{
"interest" : "Loveoor",
"sports" : "Table Tennis"
}
],
"_class" : "com.example.Person"
}
/* 2 */
{
"_id" : ObjectId("5ca746fd92bc0733a4a6633c"),
"firstName" : "Neha",
"lastName" : "Parate",
"emailId" : "[email protected]",
"hobbies" : [
{
"interest" : "Indoor",
"sports" : "Chess"
},
{
"interest" : "Loveoor",
"sports" : "Table Tennis"
},
{
"interest" : "Happydoor",
"sports" : "Lawn Tennis"
}
],
"_class" : "com.example.Person"
}
当我做db.person.distinct('hobbies')
时,我很容易得到明显的记录。
[
{
"interest" : "Indoor",
"sports" : "Chess"
},
{
"interest" : "Loveoor",
"sports" : "Table Tennis"
},
{
"interest" : "Happydoor",
"sports" : "Lawn Tennis"
}
]
我想用Spring Data Mongo或MongoTemplate做同样的事情。但事情没有办法。
@Query(value = "{}", fields = "{'hobbies' : 1}")
List<Person> findByDistinctHobbies();
在最新版本的Spring Data Mongo中,根据文档:https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongo-template.query.distinct。您甚至可以查询嵌入的文档以查找distinct
文档。
通过MongoTemplate,你可以实现如下:
List<Object> object = mongoTemplate.query(Person.class).distinct("hobbies").all();
for (Object object2 : object) {
Hobbies hobbies = (Hobbies) object2;
System.out.println(hobbies);
}
}