levi.hrb
levi.hrb

Reputation: 51

Mongo: Use field value as pipeline from-collection

I want to use the value of a field as the value for the from-collection of a pipeline.

  [
    {
        $addFields: {
            fromCollection: 'mycollection' // this would be of course a value of the object
        }
    }, 
    {
        $lookup: {
            from: '$fromCollection', // here I want to use a field reference, not a static value
            pipeline: [ ... ],
            as: 'test'
        }
    }
]

But this isn't working, if I use instead the value directly in the lookup: 'from': 'mycollection' everything works as expected. Is there any way I can use the value of a field as the from-collection-name?

MongoDB Version: db version v5.0.5

Upvotes: 0

Views: 218

Answers (1)

Wernfried Domscheit
Wernfried Domscheit

Reputation: 59523

Maybe an approach like this is suitable:

var mycollectionData = db.getCollection("mycollection").findOne({...})

[
    {
        $addFields: {
            test: mycollectionData
        }
    } 
]

If your collection has more than one document, then localField/foreignField can be simulated like this:

var mycollectionData = db.getCollection("mycollection").find({...}).toArray()

[
    {
        $addFields: {
            test: { 
              $filter: { 
                 input: mycollectionData, 
                 as: "foreign",
                 cond: {$eq: ["$$foreign._id", "$_id"] } 
              } 
           }
        }
    } 
]

Upvotes: 1

Related Questions