How can I use a dynamic path in my MongoDB aggregation pipeline to assign the value of 'address.city' to a field named 'fieldName' using the $getField operator? The current query I have doesn't seem to be working as expected. Just a little note- I want to keep "fieldName" in order to calculate dynamically the path.
db.collection.aggregate([
{
$addFields: {
fieldName: "address.city",
}
},
{
$addFields: {
fieldValue: {
$getField: {
field: "$fieldName",
input: "$$ROOT"
}
}
}
}
])
Write this as an answer from the comment as it resolves the Post Owner's question.
Unfortunately, it is not possible to access the value as the field name in the $getField
or other operator.
But what you can achieve is:
Convert the key-value pair to an array of objects consisting of k
and v
fields via $objectToArray
.
Filter the matched object by matching the value of k
via the $filter
operator.
Convert the array of objects to a key-value pair via $arrayToObjectt
.
{
$set: {
linkedStreets: {
$objectToArray: "$linkedStreets"
}
}
},
{
"$project": {
"fieldValue": {
$arrayToObject: {
$filter: {
input: "$linkedStreets",
cond: {
$eq: [
"$$this.k",
"$$steertType"
]
}
}
}
}
}
}