Skip to content
Advertisement

Expand a variable in a MongoDB aggregation pipeline

In a Typesctipt code, I would like to use a varible value in an aggregation pipeline in MongoDB; the problem is that the “keyToCheck” field is a variable that is set by the Typescript code and, therefore, can change based by many conditions. Is there a way to expand the variable “keyToCheck”? I have tried $$keyToCheck, $keyToCheck with no result (compilation errors). Thanks.

...
const pipeline = [
                {
                    $match: {
                        [this.countryOriginFieldName!]: {
                            $in: members
                        },
                        **keyToCheck**: {
                            $nin: dictionaryNotAbsoluteFieldList
                        }
                    }
                },
...

UPDATE: try with this example:

var keyToCheck = "indicator";
var queryMatch = {"`$${keyToCheck}`": "US$millions"}
printjson(queryMatch);

db.getCollection("temp_collection").aggregate([
 {
  $match: queryMatch
 },
 {$project: {indicator: 1, value: 1}}
 ]
);



db.getCollection("temp_collection").insertMany([
{ 
    "indicator" : "US$millions", 
    "value" : 1.0
},
{ 
    "indicator" : "US$millions", 
    "value" : 2.0
},
{ 

    "indicator" : "EUROmillions", 
    "value" : 3
}
]);

Desired output:

{ 
    "indicator" : "US$millions", 
    "value" : 1.0
}
{ 
    "indicator" : "US$millions", 
    "value" : 2.0
}

Advertisement

Answer

Query

  • the [keyToCheck] is to take the value of the variable, its not an array
  • here its assumed that you want to project also the keyToCheck, and not always project the indicator
var keyToCheck = "indicator";

db.getCollection("temp_collection").aggregate([
 {
  $match: {[keyToCheck]: "US$millions"}
 },
 {$project: {[keyToCheck]: 1, value: 1}}
 ]
);

This will work, key will be just a string,and in project also just a string. You dont need $ or $$ with this query.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement