Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

141
Views
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
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!