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

176
Visualizações
How to $match a field conditionally in mongo DB

I have the following schema:

User: {
...otherFields,
isDumb: false,
type: "A" // could be "A", "B", or "C"
}

I want to fetch all dumb users by default and fetch by type only if the type is passed through the parameters.

    static async getUsers(req: any, res: Response) {
        const { type = "" } = req.params;
        const queryPipeline = [
            {
                $match: {
                    isDumb: true,
                    type: // I want to only filter by type if the param is passed in
                }
            }
         ]
         const users = await User.aggregate(queryPipeline);

So if my data was:

[
  {
    ...otherFields,
    isDumb: false,
    type: "A"
  },
  {
    ...otherFields,
    isDumb: true,
    type: "B"
  },
  {
    ...otherFields,
    isDumb: true,
    type: "C"
  }
]

and req.params.type was "B", I should get back:

[
  {
    ...otherFields,
    isDumb: true,
    type: "B"
  }
],

if req.params.type was undefined, I should get all dumb users

[
  {
    ...otherFields,
    isDumb: true,
    type: "B"
  },
  {
    ...otherFields,
    isDumb: true,
    type: "C"
  }
]
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

you just have to build an object and pass it to match

const matchParams = req.params.type ? {isDumb:true,type:req.params.type } : {isDumb:true }
about 4 years ago · Juan Pablo Isaza Relatório

0

You can create the object using JS:

const params = "A" // get req.params as you want
let query = {$match:{isDumb:true}}
if(params) query.$match.type = params

console.log(query)

about 4 years ago · Juan Pablo Isaza Relatório

0

First, you don't need to use Aggregation Framework for simple find query. You can use find method instead.

Second, consider approach where you initialize the filter with isDumb: true, and add new type property only if req.params.type exists.

let filter = { isDumb: true };
if(req.params.type) filter.type = req.params.type;

const users = await User.find(filter);
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