How can I implement addFields mongoDB query in Java

Sheel :

I have found several example at StackOverFlow related to addFields in Aggregation. But no one implemented in Java.

db.getCollection('myDocument').aggregate([
    {$match : {"metaId.ref.uuid" : "d6112808-1ce1-4545-bd52-cf55bc4ed25e"}},
    {$lookup: {from: "simple", localField: "someId.ref.uuid", foreignField: "uuid", 
    as: "simple"}},
    {"$unwind": "$simple"},
    {"$addFields": { "metaId.ref.name" : "$simple.name" }}
])

I am not able to Implement In Java Correctly:-- Not getting proper procedure

   LookupOperation lookupOperation =LookupOperation.newLookup().from("simple").localField("execId.ref.uuid").foreignField("uuid").as("simple");
            Aggregation myDocAggr = newAggregation(match(Criteria.where("metaId.ref.uuid").is(someUUID)), group("uuid").max("version").as("version"),
                    lookupOperation,
                    Aggregates.unwind(""),
                Aggregates.addFields(fields));
            Document document =new Document();
            AggregationResults<String> myDocAggrResults = mongoTemplate.aggregate(myDocAggr , myDocument, myDocument.class);
            List<String> mydocumentList = myDocAggrResults .getMappedResults();

Not able to use unwind and addFields, this is sample java code, but it is not ok. Please help me. Thanks in advance

user2683814 :

You are mixing the java driver Aggregates method with Spring Aggregation methods.

Also $addFields is still not supported in spring mongo.

You have to use below aggregation.

import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
Aggregation myDocAggr = newAggregation(
       match(Criteria.where("metaId.ref.uuid").is(someUUID)), 
       group("uuid").max("version").as("version"),
       lookup("simple","execId.ref.uuid","uuid","simple"),
       unwind("simple"),
       new AggregationOperation(){ 
         @Override 
         public Document toDocument(AggregationOperationContext aoc) {
            return new Document("$addFields",new Document("metaId.ref.name","$simple.name"));
         }
      }
)
List<Document> mydocumentList=mongoTemplate.aggregate(myDocAggr,"myDocument",Document.class).getMappedResults();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=73541&siteId=1