Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic keys from values in MongoDB

Say I have this:

{
        "_id" : "ENVD",
        "years" : [
                {
                        "year" : "2013",
                        "avgInstructor" : 5.144999999999998
                },
                {
                        "year" : "2012",
                        "avgInstructor" : 5.194436090225564
                }
        ]
}

I need to be able to find the difference in the avgInstructor field from 2012-13. I was thinking I could transform the keys somehow using a $project which would make the year be the key, and the avgInstructor rating be the value. So it would look like this:

{
        "_id" : "ENVD",
        "years" : {
                        "2013" : 5.144999999999998,
                        "2012" : 5.194436090225564
         }

}

Is this possible? Keep in mind my main goal is to be able to run a subtraction like this pseudocode : years['2013'].avgInstructor - years['2013'].avgInstructor. So if you see an easier way, that would be great as well. I am not sure of the best way to go about this in the context of an aggregation pipeline. Can someone help?

like image 542
ianks Avatar asked Jan 19 '15 20:01

ianks


1 Answers

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"
            ]
          }
        }
      }
    }
  }
like image 108
thammada.ts Avatar answered Nov 02 '22 10:11

thammada.ts