Home > Net >  Retrieve value from array of objects
Retrieve value from array of objects

Time:12-01

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.

CodePudding user response:

Query

  • the items array is almost ready to become document {}
  • $map to rename key->k and value->v (those are the field names mongo needs)
  • $arrayToObject to make the items [] => {}
  • and then merge items document with the root document
  • and project the items {} (we don't need it anymore the fields are part of the root document now)

*you can combine the 2 $set in 1 stage, i wrote it in 2 to be simpler

Test code here

aggregate(
[{"$set": 
    {"items": 
      {"$map": 
        {"input": "$items", "in": {"k": "$$this.key", "v": "$$this.value"}}}}},
  {"$set": {"items": {"$arrayToObject": ["$items"]}}},
  {"$replaceRoot": {"newRoot": {"$mergeObjects": ["$items", "$$ROOT"]}}},
  {"$project": {"items": 0}}])

CodePudding user response:

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

        }
    }
}, {
    $project: {
        items: {
            $arrayToObject: "$items"
        }
    }
}])

Test Code

  • Related