how do i merge a value array with a key name in a mongodb?

You can try,

  • $arrayToObjects to set foo as k(key) and bar as v(value) and convert to object format
  • $mergeObjects to merge $$ROOT and above operation result
  • $replaceRoot to replace above both merge object result in root
  • $project to remove bar field because we don’t needed
db.collection.aggregate([
  {
    $replaceRoot: {
      newRoot: {
        $mergeObjects: [
          { $arrayToObject: [[{ k: "$_id.foo", v: "$bar" }]] },
          "$$ROOT"
        ]
      }
    }
  },
  { $project: { bar: 0 } }
])

Playground

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top