Mongodb aggregation

Hello guys.
I have read in documentation that if you want to get access to some object property you should use . notation:

If the variable references an object, to access a specific field in the object, use the dot notation; i.e. "$<variable>.<field>" .

But in my case, i dont know the key. I have some variable, for example $$this.field that store my object key.
And if i try to do $$variable[$$this.field] i have an error:
contains an invalid character for a variable name: ‘[’

So, how to read object key dynamically?

for this, you need to use $getField function. for example, to get product.price use the following.
{
$getField: {
field:“price”,
input:"$product"
}
}
you can fetch the field from another property.

$getField (aggregation) — MongoDB Manual

1 Like