在Spring Mongo中作为嵌套文档项目

时间:2018-11-08 17:26:53

标签: java mongodb aggregation-framework spring-data-mongodb

我正在寻找翻译人员来更改此内容:

getCollection('migrate').aggregate([  
{ "$project": {  
"Contrat": {"Field1":"$Field1", "Field2":"$Field2"},
"Formule": {"Field3":"$Field3", "Field4":"$Field4"}  
    }},  
    { "$project": {  
      "Contrats": {"Contrat":"$Contrat", "Formule":"$Formule"}  
    }}  
])  

MongoJava聚合框架。像

AggregationOperation project = Aggregation.project("Field1,Field2");  // while naming it "Contrat"
AggregationOperation project2 = Aggregation.project("Field3,Fiel4");  // while naming it Formule
AggregationOperation project3 = Aggregation.project("Contrat,Formule");   // while naming it " Contrats"

AggregationOperation out = Aggregation.out("test");

Aggregation aggregation = Aggregation.newAggregation(project, project2, project3, out);

mongoTemplate.aggregate(aggregation, "<nameOfInitialCollection>", Class.class);

我在文档中找不到答案,我认为它太糟糕了,否则我可能会迷失其中(|愚蠢)。

我会先谢谢你。

1 个答案:

答案 0 :(得分:1)

您可以使用以下汇总。

AggregationOperation project = Aggregation.project().
         and("Contrat").nested(Fields.fields("Field1","Field2")).
         and("Formule").nested(Fields.fields("Field3","Field4"));
AggregationOperation project2 = Aggregation.project().
         and("Contrats").nested(Fields.fields("Contrat","Formule")).
AggregationOperation out = Aggregation.out("test");

Aggregation aggregation = Aggregation.newAggregation(project, project2, out);
mongoTemplate.aggregate(aggregation, "<nameOfInitialCollection>", Class.class);