Spring data mongodb应用程序设计和数据聚合
我正在用和开发一个小应用程序。 以下是模型:Spring data mongodb应用程序设计和数据聚合,spring,mongodb,aggregation-framework,aggregate,spring-data-mongodb,Spring,Mongodb,Aggregation Framework,Aggregate,Spring Data Mongodb,我正在用和开发一个小应用程序。 以下是模型: public class Lease { @Id private String id; private long created; private Lessor lessor; private Lessee lessee; } public class Payment { @Id private String id;
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并以自己的形式编辑它。
在应用程序的主页上,它显示了按月付款的租赁列表。在列表上方的选择框中选择年份
如何更好地使用rest按年按月加载带有付款的租约:可能是先加载租约,然后向付款注入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();
问题在于,match在这里是排他性的,例如,如果2017年没有付款,则租约列表为空。我在mongo中看到了“addFields”功能,因为它尚未在SpringDataMongoDB中实现。对我来说,更好的json回报是:
{"leases" : [{"id" : 123, "created" : 12324343434, "payments" : [123, 455, 343, 323, 344, null, null, 332, 323, 232, 333, 434}]}
其中付款将代表特定年份的十二个月
我如何使用spring data mongodb获得此信息
任何帮助都将不胜感激 每当Spring Data Mongo缺少所需的聚合操作时(为了重现
$addFields
,$redact
…),一个解决方法(有些人可能会说快速而肮脏的解决方案)是直接使用com.mongodb.client工具将原始聚合传递给Spring:
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" : { ... } } */)))
String collectionName=mongoTemplate.getCollectionName(Payment.class);
MongoCollection collection=mongoClient.getDatabase(mongoTemplate.getDb().getName()).getCollection(collectionName);
AggregateIterable ai=collection.aggregate(Arrays.asList(
parse(/*{“组”:{…}}*/))
MongoCollection.aggregate()作为List
(实际上是List)传递给聚合管道