0

我开发一个小应用程序与spring data mongoangularjs。 这里是模型:春数据MongoDB的应用程序设计和数据聚合

public class Lease { 
     @Id 
     private String id; 
     private long created; 
     private Lessor lessor; 
     private Lessee lessee; 
     } 

public class Payment { 
     @Id 
     private String id; 
     private Integer month; 
     private Integer year; 
     private Long amount; 
     private String leaseId; 
    } 

我并没有插入支付模型,我需要它有一个ID,并在其自己的形式编辑。 在应用程序的主页上,它代表按月付款的租赁列表。在列表中选择一年。

如何更好地利用余额逐月加载租赁:可能是首次加载租赁,然后将ID注入付款或有更好的解决方案?目前我选择使用聚合:

LookupOperation lookupOperation = LookupOperation.newLookup(). 
            from("payment"). 
            localField("leaseId"). 
            foreignField("id"). 
            as("payments"); 

AggregationOperation match = Aggregation.match(Criteria.where("payments.year").is(year)); 
Aggregation aggregation = Aggregation.newAggregation(lookupOperation, match); 

return mongoOperations.aggregate(aggregation, "lease", LeaseAggregation.class).getMappedResults(); 

的问题是,比赛是唯一在这里和例如如果在2017年没有支付,租赁的列表是空的。我看到mongo中的“addFields”功能尚未在spring数据mongodb中实现。对我来说更好的json回报将是:

{"leases" : [{"id" : 123, "created" : 12324343434, "payments" : [123, 455, 343, 323, 344, null, null, 332, 323, 232, 333, 434}]} 

付款将代表某个特定年份的12个月。

如何用spring数据mongodb获得这个?

任何帮助,将不胜感激!

回答

0

每当春天数据蒙戈没有你需要的AggregationOperation(重现$addFields$redact ...),解决方法(有些人可能会说,快速和肮脏的解决方案)是通过将原始聚集到春天,直接使用该com.mongodb .client工具:

String collectionName = mongoTemplate.getCollectionName(Payment.class); 
MongoCollection<Document> collection = mongoClient.getDatabase(mongoTemplate.getDb().getName()).getCollection(collectionName); 

AggregateIterable<Document> ai = collection.aggregate(Arrays.asList(
    Document.parse(/* { "group" : { ... } } */))) 

MongoCollection.aggregate()是通过聚合管道为List<Document>(其实List<? extends Bson>原始形式使用上述Document.parse()所建议的,你当然也可以使用new Document(),使它看起来更像是正确的OOP代码,当原始聚合非常复杂或嵌套组件很多时,我倾向于使用原始形式嵌套文档的nts对我来说太冗长了,但这是一个有趣的问题。