'is there any workarround on $nin slowness on mongoDB?

I'm implementing a pipeline on mongo which have this structure:

db.COLLECTION.aggregate([
    {
        $match: {
            $or: [
                {
                    "code": { $nin: ArrayOfValidCodes },
                    "Type": { $in: ["T1", "T2"] },
                    "date": { $lte: myDate }  
                },
                {
                    "code": { $nin: ArrayOfValidCodesForT3 },
                    "Type": { $in: ["T3"] },
                    "date": { $lte: myDate }
                }
            ]
        }
    },
    { 
        $project: {
            _id: 1,
            code: 1,
        },
    },
    {
        "$sort": { _id : -1 }
    },
    {
        "$limit": 100
    }
])

As I read from this question $nin is considerably slower than an $in but is there any workarround?

This code property sometimes is modified incorrectly by people so I want to get those invalid codes to fix them.



Solution 1:[1]

I would try to add index to "code property" and then filter by utilizing $regexMatch. https://www.mongodb.com/docs/manual/reference/operator/aggregation/regexMatch/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tomov Nenad