使用Spring Data Mongo从文档中找到不同的嵌入式文档? [英] find distinct embedded documents from the document using Spring Data Mongo?
问题描述
如何使用Spring Data Mongo或MongoTemplate或MongoOperations从嵌入式文档中删除重复项?
How to remove duplicates from the embedded documents using the Spring Data Mongo or MongoTemplate or MongoOperations?
如果我这样做
db.inventory.distinct( "hobbies" )
这给了我所有与众不同的爱好,但是如果我喜欢下面的内容,那么我就不会得到与众不同的记录.
This gives me all distinct hobbies, but if I do like below then I don't get distinct records.
示例文档:
{
"_id" : ObjectId("592c7029aafef820f432c5f3"),
"_class" : "lankydan.tutorial.mongodb.documents.Person",
"firstName" : "John",
"secondName" : "Doe",
"dateOfBirth" : ISODate("2017-05-29T20:02:01.636+01:00"),
"address" : [
{
"addressLineOne" : "19 Imaginary Road",
"addressLineTwo" : "Imaginary Place",
"city" : "Imaginary City",
"country" : "US"
},
{
"addressLineOne" : "22 South Road",
"addressLineTwo" : "South Place",
"city" : "CA",
"country" : "US"
}
],
"profession" : "Winner",
"salary" : 100,
"hobbies" : [
{
"name" : "Badminton"
},
{
"name" : "TV"
}
]
}
{
"_id" : ObjectId("592c7029aafef820f432c9h0"),
"_class" : "lankydan.tutorial.mongodb.documents.Person",
"firstName" : "Shrutika",
"secondName" : "Parate",
"dateOfBirth" : ISODate("2017-05-29T20:02:01.636+01:00"),
"address" : [
{
"addressLineOne" : "20 Love Road",
"addressLineTwo" : "Love Place",
"city" : "Imaginary City",
"country" : "US"
},
{
"addressLineOne" : "22 North Road",
"addressLineTwo" : "North Place",
"city" : "LA",
"country" : "UK"
}
],
"profession" : "Winner",
"salary" : 100,
"hobbies" : [
{
"name" : "Badminton"
},
{
"name" : "TV"
},
{
"name" : "Cricket"
},
{
"name" : "Tenis"
}
]
}
Spring Data Mongo查询:
Spring Data Mongo Query:
@Query(value = "{}", fields = "{'hobbies' : 1}")
List<inventory> findByHobbiesDistinctName();
推荐答案
我能够使用最新版本的 Spring Boot Mongo 和 Spring Boot 解决此问题.库v 2.1.4.RELEASE.
I was able to solve this issue by using latest version of Spring Boot Mongo and using Spring Boot library v 2.1.4.RELEASE.
更多详细信息可从此处引用: https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongo-template.query.distinct
More details can be referred from here: https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongo-template.query.distinct
List<Object> object = mongoTemplate.query(Person.class).distinct("hobbies").all();
for (Object object2 : object) {
Hobbies hobbies = (Hobbies) object2;
System.out.println(hobbies);
}
这很好用.
这篇关于使用Spring Data Mongo从文档中找到不同的嵌入式文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!