Home > Mobile >  Mongoose don't select the record that didn't joined with any, at $lookup
Mongoose don't select the record that didn't joined with any, at $lookup

Time:07-06

I am able to successfully implement the lookup, but the problem is that; I don't need the records which doesn't have any record to join in child collection. Currently I am getting blank array for child field, if no matching record found in child collection. Note: I am using MongoDB Flexible Schema

parentCollection.aggregate([ 
    { 
        '$match': { 
            userId: '62810c69e880ed667073add1',
            type: 'data' 
        } 
    }, 
    { 
        '$lookup': { 
            from: 'childCollection', 
            let: { typeId: { '$toObjectId': '$typeId' } }, 
            pipeline: [ { 
                '$match': { 
                    '$expr': { '$eq': [ '$_id', '$$typeId' ] }, 
                    '$or': [ { 
                        'field1': { '$regex': '737', '$options': 'i' } 
                    }, 
                    { 
                        'field2': { '$regex': '737', '$options': 'i' } 
                    }] 
                }
            }], 
            as: 'child' 
        } 
    }, 
    { '$limit': 10 }, { '$skip': 0 }], 
{});

CodePudding user response:

I have achieved this by adding an additional $match on child after $lookup

parentCollection.aggregate([ 
        { 
            '$match': { 
                userId: '62810c69e880ed667073add1',
                type: 'data' 
            } 
        }, 
        { 
            '$lookup': { 
                from: 'childCollection', 
                let: { typeId: { '$toObjectId': '$typeId' } }, 
                pipeline: [ { 
                    '$match': { 
                        '$expr': { '$eq': [ '$_id', '$$typeId' ] }, 
                        '$or': [ { 
                            'field1': { '$regex': '737', '$options': 'i' } 
                        }, 
                        { 
                            'field2': { '$regex': '737', '$options': 'i' } 
                        }] 
                    }
                }], 
                as: 'child' 
            } 
        },{
            $match: {
                $expr: {
                    $gt: [{
                        $size: '$child'
                    }, 0]
                }
            }
        },
        { '$limit': 10 }, { '$skip': 0 }], 
{});
  • Related