2

I have 3 collections: 'group10', 'group20' and 'parent'

I want to do $lookup in aggregation pipeline from one of these collections depending from condition in 'parent' collection.

Collection 'parent':

[{_id: 1, groupId: 10},
 {_id: 2, groupId: 20}]

Collection 'group10':

[{_id: 1, groupId: 10, userData: 'A'},
 {_id: 2, groupId: 10, userData: 'B'}]

Collection 'group20':

[{_id: 1, groupId: 20, userData: 'C'},
 {_id: 2, groupId: 20, userData: 'D'}]

I tried next code:

$lookup: {
    from: {
        $cond: [{
                $eq: ['$groupId', 10]
            },
            'group10',
            'group20'
        ]
    },
    localField: 'groupId',
    foreignField: 'groupId',
    as: 'data'
}

but getting this error: 'from' option to $lookup must be a string, but was type object

Kirill
  • 41
  • 1
  • 5
  • 1
    Possible duplicate of [Mongodb $lookup dynamic collection](https://stackoverflow.com/questions/39902878/mongodb-lookup-dynamic-collection) – sheilak May 19 '19 at 10:54

1 Answers1

1

I searched and I found out mongo doesn't permit to use from in lookup as a dynamic field but I could solve your issue with these

[
    {
        '$lookup': {
            'from': 'group10', 
            'localField': 'groupId', 
            'foreignField': 'groupId', 
            'as': 'datagroup10'
        }
    }, {
        '$lookup': {
            'from': 'group20', 
            'localField': 'groupId', 
            'foreignField': 'groupId', 
            'as': 'datagroup20'
        }
    }, {
        '$project': {
            'data': {
                '$switch': {
                    'branches': [
                        {
                            'case': {
                                '$eq': [
                                    '$datagroup20', []
                                ]
                            }, 
                            'then': '$datagroup10'
                        }
                    ], 
                    'default': '$datagroup20'
                }
            }
        }
    }
]

if you have more collection you could add another lookup and add condition at $switch case or do collection detection in the application layer

mohammad Naimi
  • 2,259
  • 1
  • 5
  • 15
  • Any code example? Please also [edit](https://stackoverflow.com/posts/68876863/edit) and format your answer to improve readability. – HardcoreGamer Aug 23 '21 at 09:07