mongodbmongodb-queryaggregation-frameworkmorphia

Convert array of objects, to object


I have a mongo db record like this

items: [
  0: {
    key: name,
    value: y
   },
  1: {
     key: module,
     value: z
   }
]

And per record my expected output is this

{
  name : y,
  module : z
}

What is the best mongo db aggregation i should apply to achieve this. I have tried few ways but i am unable to produce output. We can't use unwind otherwise it will break the relationship between name and module.


Solution

  • aggregate(
    [{
        $project: {
            items: {
                $map: {
                    input: "$items",
                    "in": {
                        "k": "$$this.key",
                        "v": "$$this.value"
                    }
                }
    
            }
        }
    }, {
        $project: {
            items: {
                $arrayToObject: "$items"
            }
        }
    }])
    

    Test Code