I`m trying to add a field representing relative weights to documents in an array. I have the following data model shown here with two documents:
db.pos.insertMany([
{"asof": "2020-02-05",
"holdings": [
{"fid": 1,"shares": 50},
{"fid": 2,"shares": 50}
],
"portfolio_id": 10,
"user": "xxx"
},
{"asof": "2020-02-02",
"holdings": [
{"fid": 1,"shares": 40},
{"fid": 2,"shares": 60},
{"fid": 3,"shares": 30}
],
"portfolio_id": 10,
"user": "xxx"
}]);
Now, for each document in the array field "holdings" I`m trying to add "wt" which is simply shares/sum(shares), where sum is taken over all documents within holdings. My goal is to return the whole document with the "wt" addition, so the end result would look somethig like this:
{ "_id": ObjectId()
"asof": "2020-02-05",
"holdings": [
{"fid": 1,"shares": 50, "wt": 0.5},
{"fid": 2,"shares": 50, "wt": 0.5}
],
"portfolio_id": 10,
"user": "xxx"
},
{"_id": ObjectId()
"asof": "2020-02-02",
"holdings": [
{"fid": 1,"shares": 40, "wt": 0.3076923},
{"fid": 2,"shares": 60, "wt": 0.4615384},
{"fid": 3,"shares": 30, "wt": 0.2307692}
],
"portfolio_id": 10,
"user": "xxx"
}
I have tried routes/stages using $addField or $project together with $map ($divide and $sum) and some are closer to the desired result than others. But, I am nowhere near getting "inplace" results as shown above. Anyone able to help me out?