Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

143
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda