Spring Data Mongo与众不同不起作用。我正在看两个文件。
/* 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"
}
当我做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();
答案 0 :(得分:2)
根据文档https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongo-template.query.distinct在最新版本的 Spring Data Mongo 中。您甚至可以查询嵌入的文档以找出distinct
个文档。
通过MongoTemplate,您可以实现以下效果:
List<Object> object = mongoTemplate.query(Person.class).distinct("hobbies").all();
for (Object object2 : object) {
Hobbies hobbies = (Hobbies) object2;
System.out.println(hobbies);
}
}