Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

142
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda