Project as nested document in spring mongo

拥有回忆 提交于 2019-12-02 13:52:09

问题


I'm looking for a translator to change this :

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

to MongoJava aggregation framework. Something like :

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);

I can't find my answers in the documentation, which I think is too poor, or I may be too lost in it ( | dumb).

I'll thank you in advance.


回答1:


You can use below aggregation.

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);


来源:https://stackoverflow.com/questions/53213134/project-as-nested-document-in-spring-mongo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!