Add fields based on deeply nested values

In my pipeline I’m trying to connect documents that have a deeply nested values that I wanted to get on top by saving then in new added fields. But since they are stored inside multidimensional arrays I’m unable to get them thu numeric indexes.

Not sure what am i doing wrong:

    db.OrderAttributes.aggregate([
       {
         $lookup:
           {
             from: "Orders",
             localField: "OrderId",
             foreignField: "OrderId",
             as: "orderdata"
           }
      },
      {
        $match:{
            RulesetInfluencedAttributes: {$elemMatch: {
            LexisAttributes:{$elemMatch: {
                "myattributes.myvalue":{$ne:null}
            }
                
            }
        }} 
        }  
      },
      { 
          $addFields: { 
            test: "$RulesetInfluencedAttributes.0.LexisAttributes.0.myattributes.myvalue" <-- this returns empty array                
            }}
          } 
          
      },

It will be helpful to give the data,and the wanted final result.

But if the only problem is that paht in $addFields , you can fix it.
You need to use arrayElemAt

.fieldName is ok
.index doesnt work in aggregation (use arrayElemAt)

You can do it by hand using temporal variables.
Or you can make a driver function that generates that MQL code.

My generator function for your path gave

{"$addFields" {"test" {"$let" {"vars" {"v0" {"$let" {"vars" {"v0" {"$arrayElemAt" [{"$let" {"vars" {"v0" {"$arrayElemAt" ["$RulesetInfluencedAttributes" 0]}}, "in" "$$v0.LexisAttributes"}} 0]}}, "in" "$$v0.myattributes"}}}, "in" "$$v0.myvalue"}}}}

By hand its a bit smaller

{"$addFields" {"test" {"$let" {"vars" {"v0" {"$arrayElemAt" ["$RulesetInfluencedAttributes" 0]}}, "in" {"$let" {"vars" {"v1" {"$arrayElemAt" ["$$v0.LexisAttributes" 0]}}, "in" "$$v1.myattributes.myvalue"}}}}}}