'Is there a way to join 2 different mongo collections of the same database and return as one JSON / map data in Java Spring using mongoTemplate?

I have 2 collections , coll1 , coll2. There are so many fields and multiple data records in the 2 collections including redundant fields and values.

When I try in NoSQL Booster (Mongo):

db.coll1.aggregate( [
   {
     $lookup:
       {
         from: "coll2",
         localField: "v_reg",
         foreignField: "v_reg",
         as: "v_data"
       }
   },
   {
     $match: { "v_data": { $ne: [] } }
  }
  
] )

It works fine.

But when tried to implement this in Java, it is resulting in only one of the collection in the result and not 2 joined as one.

Below are my attempts, but none is correct.

public void joinAggr() {
        
        LookupOperation lookupOperation1 = LookupOperation.newLookup()
                .from("coll2")
                .localField("v_reg")
                .foreignField("v_regn")
                .as("vhe_info");
        
//Aggregation.lookup("coll1", "v_reg", "v_reg","d_info");

        AggregationOperation match0 = Aggregation.match(Criteria.where("vhe_info").size(1));
        AggregationOperation match1 = Aggregation.match(Criteria.where("v_reg").size(1));
    

        Aggregation agg1 = Aggregation.newAggregation(              
                lookupOperation1,
                match0
            );
        
//      mongoTemplate.aggregate(agg, "coll1", OutputDocument.class);
        AggregationResults<Device> aggResult1 = mongoTemplate.aggregate(agg1, "coll1", Coll1.class);
        List<Device> dataList1 = aggResult1.getMappedResults();
        AggregationResults<Vehicle> aggResult2 = mongoTemplate.aggregate(agg1, "coll1", coll2.class);
        List<Vehicle> dataList2 = aggResult2.getMappedResults();
        
//      AggregationResults<Document> aggResult3 = mongoTemplate.aggregate(agg1, coll2.class, Document.class);
//      AggregationResults<Document> aggResult4 = mongoTemplate.aggregate(agg1, coll1.class, Document.class);
//      List<Document> dataList3 = aggResult3.getMappedResults();
//      dataList3.add((Document) aggResult4.getMappedResults());
        
        
        
        
         AggregationResults<Result> aggResults = mongoTemplate.aggregate(agg1, Coll2.class, Result.class);
           List<Result> dataList = aggResults.getMappedResults();
          
           AggregationResults<Result> aggResult5 = mongoTemplate.aggregate(agg1, mongoTemplate.getCollectionName(coll1.class), Result.class);
           List<Result> dataList5 = aggResult5.getMappedResults();  
            

    }

I tried creating different classes to accommodate the results of aggregation lookup operations.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source