Mongo DB Attribute Pattern: Is it possible to sort by attribute value?

I’m trying to build my collection with Attribute Pattern.

The format like this JSON below

{
  name: 'Some product',
  properties_B: [
    { name: 'color', value: 'red' },
    { name: 'size', value: 43 },
    { name: 'wheels', value: 4 },
    { name: 'expression', value: 'cool'}
  ],
  ...
}

Is it still possible to sort by size or wheels ?

One possible approach would be to use a $set stage with a $reduce of properties_B to extract the value, then the $sort it self.

Something like the untested:

{ $set: {
  _tmp.sort : { $reduce: {
     input: "$properties_B" , 
     initialValue : 0 ,
     in : { $cond : [
       { $eq : [ "$$this.name" , "size" ] } ,
       "$$this.value" ,
       "$$value"
     ] }
  } }
} }

After this stage you may $sort with _tmp.sort:1.

Note that I put my temporary fields into a _tmp object. This way a simple $unset:_tmp remove all the temporary variables from the result set.

Dear @jowy_atreides, It has been a few days since I provided input on your issue.

I spent time on your issues and I would appreciate a followup and perhaps closure.

Other users of the forum would also appreciate as they may have similar issues and would gain by knowing what worked and what did not.

Thanks