Mongo DB aggregation using Compass - use variable as key name

Viewed 584

I'm trying to map an array of objects to a new array of objects. An example of the object in the array:

{
   k:"Zip code"
   v:{
      questionId:"596080353"
      question:"In which ZIP code do you currently reside?"
      answer:"97213"
   }
}

I want the final object to be:

{
  "Zip code": "97213"
}

I'm having trouble setting k as the key name in the new object. Does anyone know how to use variables as the key name in a mongo aggregation?

1 Answers

Use $arrayToObject

Converts an array into a single document; the array must be either:

Shape your data in the below format

[ { "k": "Zip code", "v": "97213"}, { "k": "Zip code", "v": 97212 } ]

Example 1 - https://mongoplayground.net/p/AXKHsZf-Qzy

db.collection.aggregate([
  { $set: { doc: [ { k: "$k",  v: "$v.answer" } ] } },
  { $set: { doc: { "$arrayToObject": "$doc" } } }
])

Example 2 - https://mongoplayground.net/p/Vm1DwHVb9KY

db.collection.aggregate([ 
  { $unwind: "$zip" }, 
  { $addFields: { doc: { $arrayToObject: [ [ { k: "$zip.k", v: "$zip.v" } ] ] } } },
  { $group: { _id: "$_id", zips: { $push: "$doc" } } }
])
Related