Search code examples
mongodbmongodb-queryaggregation-frameworkspring-data-mongodbnosql-aggregation

mongodb aggregation pipeline solution for getting record from 2 collections based on the value from an array in one collection


I have two mongoDb collections, one contains data about cards and the other contains data about a field of cards and called list. structure of firstCollection :

{ 
    "cardType":"card", 
    "xyz":"XYZ", 
    "fields":[ 
        {"abc":"abc", "xyz":"XYZ", "inputMethod" : "Entry", "xyz":"xyz"}, 
        {"abc":"abc", "xyz":"XYZ", "inputMethod" : "List", "xyz":"xyz", "ListId":"1234"}
        // ListId will only be present incase of inputMethod=List 
    ] 
}

Structure of secondCollection:

{ "abc":"abc", "xyz":"xyz, "itemId": "1234" }

Now what I want is all the firstCollection where cardType = "card", complete card object and all the items from secondCollection where itemId in (select ListId from firstCollection where fields.inputmethod = "List").

Need to write MongoDB pipeline for this situation. I am quite new to mongo, it can be done using an aggregation pipeline with $loopup but I can write the pipeline. the result I want :

{
    firstCollection:{complete collection },
    secondCollection:[ 
        array of matching records from second collection where 
        secondelement.itemId in(records from array of firstcollection 
        where fields.inputmethod = "List" )
    ]
}

Solution

  • db.first.aggregate([
      {
        $match: {}
      },
      {
        $project: {
          firstCollection: "$$ROOT"
        }
      },
      {
        $lookup: {
          "from": "second",
          "localField": "firstCollection.fields.ListId",
          "foreignField": "itemId",
          "as": "secondCollection"
        }
      }
    ])
    

    mongoplayground