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對我來說太冗長了,但這是一個有趣的問題。