bc110402922
bc110402922

Reputation: 457

How to merge Array value with key name in mongo db

{
    _id :{
        "foo" : "abc"
    },
    "time" :[],
    "bar": [
        [],
        []
    ]
}

Expected Output abc become the key bar

{
    "_id" :{
        "foo" : abc
    },
    "time" :[],
    "abc": [
        [],
        []
    ]
}

Upvotes: 1

Views: 1113

Answers (1)

turivishal
turivishal

Reputation: 36114

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

Upvotes: 1

Related Questions