Dynamic keys from values in MongoDB
For people that ends up here looking for a solution to transform an array to an object using aggregation in a more recent version of MongoDB:
MongoDB 3.4.4 introduced $arrayToObject
You have to $map years
{ $set: { years: { $map: { input: "$years", as: "year", in: [ "$$year.year", "$$year.avgInstructor" ] } } } }
to be like this
{ "_id" : "ENVD", "years": [ ["2013", 5.144999999999998], ["2012", 5.194436090225564] ]}
then use $arrayToObject
{ $set: { years: { $arrayToObject: "$years" } } }
Or combine the two steps together
{ $set: { years: { $arrayToObject: { $map: { input: "$years", as: "year", in: [ "$$year.year", "$$year.avgInstructor" ] } } } } }
A Possible answer ...
- Unwind first
- project to make it a little easier to handle
- Sort on _id and then on year
- group by _id to pickup the first and the last value
final projection to get subtracted value
db.coll.aggregate ( [ { "$unwind" : "$years" } , { $project : { "year" : "$years.year", "avgInstructor" : "$years.avgInstructor" } }, { $sort : { "_id" : 1, "year" : 1 } }, { $group : { "_id" : "$_id", "val_min" : { $first : "$avgInstructor" }, "val_max" : { $last : "$avgInstructor" } } }, { $project : { "diff" : { $subtract : [ "$val_min", "$val_max" ] } } }] )