Merge documents based on "priority" value

Hi all,
i have this data so far in my aggregation:

[{
      "priority":4,
      "options":{
         "setting1":{
            "value":10
         },
         "setting2":{
            "value":20
         },
         "setting4":{
            "value":10
         },
      }
   },
   {
      "priority":1,
      "options":{
         "setting1":{
            "value":90
         },
         "setting2":{
            "value":80
         }
      }
   },
   {
      "priority":2,
      "options":{
         "setting1":{
            "value":10
         },
         "setting3":{
            "value":50
         }
      }
   }]

and i want to merge these according to their priority number (1 being the highest, 4 being the lowest)

The result should be:

{
  options: {
    "setting1": 90, // From priority: 1
    "setting2": 80, // From priority: 1
    "setting3": 50, // From priority: 2
    "setting4": 10, // From priority: 4
  }
}

Any help ?

I do not think that we have enough information to supply a complete solution but you could try the following and provide more information if it is not working.

I would start with a $sort on priority with

{ "$sort" : {
    "priority" : 1
} }

The I would $group with _id:null using the $first accumulator for the settings:

{ "$group" : {
    "_id" : null ,
    "options" : {
        "setting1" : { "$first" : "$options.setting1" } ,
        "setting2" : { "$first" : "$options.setting2" } ,
        "setting3" : { "$first" : "$options.setting3" } ,
        "setting4" : { "$first" : "$options.setting4" }
    }
} }