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
    $replaceRoot: {
      newRoot: {
        $mergeObjects: [
          { $arrayToObject: [[{ k: "$", v: "$bar" }]] },
  { $project: { bar: 0 } }


CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top