Run aggregation pipeline and sort results by a set of match priorities

As a challenge, as a learning experience and for people that cannot use Atlas search, I am trying to come up with something.

Yes it

but the concept should work.

pipeline = []

/* first stage of the pipeline is a simple regex match for ron anywhere */
_match = { "$match" : {
    "name" : { "$regex" : "ron" , "$options" : "i" }
} }

pipeline.push( _match )

/* then the magic stage, a $set that uses $cond to set 3 _sort_priorities for the 3 conditions.
   for demontration purpose I will use a simple $cond for the /^Ron / case */

_sort_priorities = { "$set" : {
    "_sort_priorities : {  "$cond" : [
        {  '$regexMatch': { input: '$name', regex: '^Ron ', options: 'i' } } ,
       0 
       1 , /* for other case we need another $cond for other cases */
    ] }
} }

pipeline.push( _sort_priorities )

/* then the final $sort  that uses _sort_priotity */
_sort = { "$sort" : {
    "_sort_priority" : 1 ,
    name : 1 
} }

pipeline.push( _sort )

The difficulty lies in the complex $cond that sets the appropriate _sort_priority. Much simpler with Atlas search but doable otherwise.

1 Like