$sortArray after $filter

Hello,

What is the right way to do $sortArray after $filter?

I have tried doing the following:

         $project: {
                products: {
                    $filter: {
                        input: "$products",
                        cond: {
                            $eq: [
                                "$$product.requiresSignature",
                                true
                            ]
                        },
                        as: "product"
                    },
                    $sortArray: {
                        input: "$products",
                        sortBy: {
                            recipient: 1.0
                        }
                    }
                }
            }

However, this will give the following error:

‘Invalid $project :: caused by :: FieldPath field names may not start with ‘$’. Consider using $getField or $setField.’

Could you kindly let me know how to correct the issue? Thank you

There are at least 2 ways.

My prefered way is to $sortArray in a separate $project such as:

{ $project: {
    products: { $filter: {
        input: "$products",
        cond: { $eq: [ "$product.requiresSignature", true ] }                       },
        as: "product"
    } },
} } ,
{ $project: {
    $sortArray: {
        input: "$products",
        sortBy: { recipient: 1.0 }
    }
} }

Or by replacing $products input on one of the expression by the other expression, such as:

{ $project: {
    $sortArray: {
        input: { $filter: {
            input: "$products",
            cond: { $eq: [ "$product.requiresSignature", true ] }                       },
            as: "product"
        } },
        sortBy: { recipient: 1.0 }
    }
} }
1 Like

Thank you! One quick question - I have noticed you have changed the $$product line, by removing 1x ‘$’ symbol. Why would that be?

cond: { $eq: [ "---->$<----product.requiresSignature", true ] }

Because I goofed.

You definitively need 2 dollar signs because product is a variable in this context.

Saru mo ki kara ochiru

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.