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

124
Visualizações
mongoose nested array filter

I have a document form similar to this

{
  "doc-id":2,
  "interfaces": [
    {
     
      "interface-role": "ON",
      "port-nb": 1
    },
    {
      
      "interface-role": "OFF",
      "port-nb": 2
    },
    {
      
      "interface-role": "ON",
      "port-nb": 3
    },
    {
      "interface-role": "OFF",
      "port-nb": 3
    }
  ]
}

I want to query and get specific document interfaces and also have the ability to filter ON and OFF and that's what I did try so far

   const doc = await this.doc
        .findOne({
          'doc-id': docId,
          'interfaces["interface-role"]': interfaceRole, //ON or OFF
        })
        .select({ interfaces: 1, _id: 0 })
        .exec();

so the result that I want to have is getting interfaces if there's no filter for interfaces-role and if there's one get the interfaces filtered

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use a $or to do the conditional filtering with a $filter.

db.collection.aggregate([
  {
    $match: {
      "doc-id": 2
    }
  },
  {
    "$addFields": {
      "interfaces": {
        "$filter": {
          "input": "$interfaces",
          "as": "i",
          "cond": {
            $or: [
              {
                $eq: [
                  null,
                  <interfaceRole>
                ]
              },
              {
                $eq: [
                  "$$i.interface-role",
                  <interfaceRole>
                ]
              }
            ]
          }
        }
      }
    }
  }
])

Here is the Mongo playground when interfaceRole is not supplied.

Here is the Mongo playground when interfaceRole is supplied.

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