Mongo 使用 Compass 的数据库聚合 - 使用变量作为键名

Mongo DB aggregation using Compass - use variable as key name

我正在尝试将一个对象数组映射到一个新的对象数组。数组中的对象示例:

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

我希望最终对象是:

{
  "Zip code": "97213"
}

我无法将 k 设置为新对象中的键名。有谁知道如何在 mongo 聚合中使用变量作为键名?

使用$arrayToObject

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

按照以下格式调整您的数据

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

示例 1 - https://mongoplayground.net/p/AXKHsZf-Qzy

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

示例 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" } } }
])