How to do a conditional sort in MongoDb Aggregate Pipeline

I wondering if there is a way to do a conditional sort in a mongoDB Aggregate pipeline.

The following is kind of what I'm trying to do but it doesn't work since sort cannot take $cond as an argument:

db.authors.aggregate([

    {
        $match: {
            _id: '562933a6bc55ca57233717ac',
        }
    },
    {
        $lookup: {
            from: 'books',
            as: 'books',
            let: { 
                authorId: '$_id',
            },
            pipeline: [
                { 
                    $match: {
                        $expr: {
                            $eq: [ '$author', '$$authorId' ]
                        }
                    }
                },
                {
                    $sort: {
                        $cond: {
                            if: {
                                $in: [
                                    '$author.type', 
                                    ['science fiction', 'fantasy']
                                ]
                            },
                            then: {
                                lastName: 1
                            },
                            else: {
                                _id: 1
                            }
                        }
                    }
                },
            ]
        } 
    },
]);

This will produce the following error:

MongoError: $meta is the only expression supported by $sort right now
728x90

0 Answers How to do a conditional sort in MongoDb Aggregate Pipeline