使用spring-data-mongodb-1.5.4mongodb-driver-3.4.2
我有一个Hotel

    public class Hotel {

        private String name;
        private int pricePerNight;
        private Address address;
        private List<Review> reviews;
//getter, setter, default constructor, parameterized constructor
Review类:
public class Review {

    private int rating;
    private String description;
    private User user;
    private boolean isApproved;
 //getter, setter, default constructor, parameterized constructor

当我调用Aggregation.unwind("reviews");时,它会抛出


UnwindOperation unwindOperation = Aggregation.unwind("reviews");
Aggregation aggregation = Aggregation.newAggregation(unwindOperation);
AggregationResults<Hotel> results=mongoOperations.aggregate(aggregation,"hotel", Hotel.class);

我看到this question,但是对我没有帮助。

如何解决呢?

最佳答案

当您使用$unwind reviews字段时,查询的返回json结构不再与您的Hotel类匹配。因为$unwind操作使reviews成为子对象而不是列表。如果您在robomongo或其他工具中尝试查询,则可以看到您的返回对象是这样的

{
  "_id" : ObjectId("59b519d72f9e340bcc830cb3"),
  "id" : "59b23c39c70ff63135f76b14",
  "name" : "Signature",
  "reviews" : {
    "id" : 1,
    "userName" : "Salman",
    "rating" : 8,
    "approved" : true
  }
}

因此,您应该使用其他类而不是Hotel之类的UnwindedHotel
public class UnwindedHotel {

    private String name;
    private int pricePerNight;
    private Address address;
    private Review reviews;
}

UnwindOperation unwindOperation = Aggregation.unwind("reviews");
Aggregation aggregation = Aggregation.newAggregation(unwindOperation);
AggregationResults<UnwindedHotel> results=mongoOperations.aggregate(aggregation,"hotel", UnwindedHotel.class);

09-30 13:04