Using a $map variable in $literal

Hi people,

New with MongoDB so still learning the ropes. I am currently writing an aggregation pipeline. Not to get into specifics (I can write them later if needed) but I am using $map and inside the map I am using $getField which uses the variable set in the $map step of the pipeline.
I use { $literal: "$$field.field_id"} for field which doesn’t seem to work.
Am I using it wrong and can $literal accept a variable from map and is there a workaround ?

Thanks

Here is an example where I use it Mongo playground. It’s a bit of a mess but the las step is where I use it

It seems that my issue isn’t that I am using variable in $literal but instead that I am trying to use $getField with a variable field name. Still not sure what the workaround for this is.

I am not sure what you expect when using $literal but $literal means that what ever follows IS NOT an expression so none of the $ or $$ will be interpreted or evaluated.

This means that in your case:

"field": {
                        "$literal": "$$content_field.field_id"
                      }

will set field literally to the string $$content_field.field_id. It will not try to evaluate the variable.

I am not sure of your intent but just using

"field":  "$$content_field.field_id"

might bring you closer to what you want.

1 Like