How to take the value from a variable as a field name?

I have a mongo db aggregation query as follows:

db.collection.aggregate([ {"$addFields" :{ “placement” : { “$indexOfArray”: [ [“Closed Won”, “Commit”, “Qualified”, “Best Case”, “Pipeline”, “Needs Review”] , “$dlf.fcst_flag.Global#Global.state" ] }}},{”$sort" : { “placement” : 1 } }]);

where I am trying to sort based on indexOfArray.

I have a field “$dlf.fcst_flag.Global#Global.state” (highlighted in the query) where the value “Global#Global” can change when I run it in a loop. Assume that the value is stored in a variable called as node… So I want to take the value of the variable node.

Output: “$dlf.fcst_flag.Global#Global.state” → “$dlf.fcst_flag.node.state” . Instead of Global#Global, I need to get the value stored inside the variable node (where node can be either Global#Global or Global or Global! or anything else ).

How can I do that?

Hi,
please format the code using backticks, like so

```
{
“$addFields”: {
“placement”: {
“$indexOfArray”: [
[“Closed Won”, “Commit”, “Qualified”, “Best Case”, “Pipeline”, “Needs Review”], “$dlf.fcst_flag.Global #Global.state " ] }}},
{”$sort": { “placement”: 1}
}
```

A few things I could not get very well, and it may help others also, if you include them.

  • Would you further explain what $dlf.fcst_flag.Global#Global.state is? Is that all a field name in a document?
  • What environment is this running on? MDB driver, Mongoose, Mongoshell…?
  • If you can include a snippet with sample document and expected output it would be great :slight_smile: