I have this Object:
{
"_id":"1",
"a":"b",
"b":"wanted value"
},
{
"_id":"2",
"a":"c",
"c":"wanted value 2"
}
how can i get the value of a and make it the property with which i project to get "wanted value"/"wanted value 2" ?
wanted output:
{
"_id":"1",
"b":"wanted value"
},
{
"_id":"2",
"c":"wanted value 2"
}
CodePudding user response:
Use $objectToArray
to convert the root document into an array of k-v tuples then use $reduce
to process the array.
db.collection.aggregate([
{
"$addFields": {
"arr": {
"$objectToArray": "$$ROOT"
}
}
},
{
"$addFields": {
// store value of field "a" into "v"
"v": {
"$reduce": {
"input": "$arr",
"initialValue": null,
"in": {
"$cond": {
"if": {
$eq: [
"$$this.k",
"a"
]
},
"then": "$$this.v",
"else": "$$value"
}
}
}
}
}
},
{
"$addFields": {
"result": {
"$reduce": {
"input": "$arr",
"initialValue": null,
"in": {
"$cond": {
"if": {
// find from k-v tuples where the field name is same as value in previously deduced "v" field
$eq: [
"$$this.k",
"$v"
]
},
"then": "$$this.v",
"else": "$$value"
}
}
}
}
}
},
{
"$project": {
// some cosmetics
arr: false,
v: false
}
}
])
Here is the Mongo playground for your reference.