1

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.

2 Answers 2

3

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}}])
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer. this answer really helped me figure another simpler approach.
its ok, replaceRoot was to get the expected output you posted, if you didn't need it you could do until $set like you did.
1
aggregate(
[{
    $project: {
        items: {
            $map: {
                input: "$items",
                "in": {
                    "k": "$$this.key",
                    "v": "$$this.value"
                }
            }

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

Test Code

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.