{
_id :{
"foo" : "abc"
},
"time" :[],
"bar": [
[],
[]
]
}
Expected Output abc become the key bar
{
"_id" :{
"foo" : abc
},
"time" :[],
"abc": [
[],
[]
]
}
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 neededdb.collection.aggregate([
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
{ $arrayToObject: [[{ k: "$_id.foo", v: "$bar" }]] },
"$$ROOT"
]
}
}
},
{ $project: { bar: 0 } }
])
{ _id :{ "foo" : "abc" }, "time" :[], "bar": [ [], [] ] } your sol is work IF [ _id :{ "foo" : "abc" }, "time" :[], "bar": [ [], [] ] ]{ } your query is working with [ ].
bartoabc. But, isabcgiven or is neccesary get from the_id.foofield?_id.foo. so,abcis dynamically changing, butbaris the key name, it contains the values ofabcExpeceted result isabcas the name of array and get values.update()this documents? or just want to get and displayaggregate()?