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

267
Visualizações
$filter inside $reduce or inside $map from array without unwind

I need some help: I want to optimize this query to be faster , it need to filter by events.eventType:"log" all docs with server:"strong" , but without separate unwind & filter stages , maybe somehow inside the $reduce stage to add $filter.

example single document:

 {
 server: "strong",
 events: [
  {
    eventType: "log",
    createdAt: "2022-01-23T10:26:11.214Z",
    visitorInfo: {
      visitorId: "JohnID"
    }
  }

current aggregation query:

   db.collection.aggregate([
   {
    $match: {
    server: "strong"
    }
   },
   {
    $project: {
     total: {
      $reduce: {
      input: "$events",
      initialValue: {
        visitor: [],
        uniquevisitor: []
      },
      in: {
        visitor: {
          $concatArrays: [
            "$$value.visitor",
            [
              "$$this.visitorInfo.visitorId"
            ]
          ]
        },
        uniquevisitor: {
          $cond: [
            {
              $in: [
                "$$this.visitorInfo.visitorId",
                "$$value.uniquevisitor"
              ]
            },
            "$$value.uniquevisitor",
            {
              $concatArrays: [
                "$$value.uniquevisitor",
                [
                  "$$this.visitorInfo.visitorId"
                ]
              ]
            }
          ]
          }
        }
       }
      }
    }
    }
    ])

expected output , two lists with unique visitorId & list of all visitorId:

 [
{
"total": {
  "uniquevisitor": [
    "JohnID"
  ],
  "visitor": [
    "JohnID",
    "JohnID"
  ]
}

} ]

playground

In the example query no filter is added for events.eventType:"log" , how can this be implemented without $unwind?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

I am not sure this approach is more optimized than yours but might be this will help,

  • $filter to iterate loop of events and filter by eventType
  • $let to declare a variable events and store the above filters result
  • return array of visitor by using dot notation $$events.visitorInfo.visitorId
  • return array of unique visitor uniquevisitor by using dot notation $$events.visitorInfo.visitorId and $setUnion operator
db.collection.aggregate([
  { $match: { server: "strong" } },
  {
    $project: {
      total: {
        $let: {
          vars: {
            events: {
              $filter: {
                input: "$events",
                cond: { $eq: ["$$this.eventType", "log"] }
              }
            }
          },
          in: {
            visitor: "$$events.visitorInfo.visitorId",
            uniquevisitor: {
              $setUnion: "$$events.visitorInfo.visitorId"
            }
          }
        }
      }
    }
  }
])

Playground


Or similar approach without $let and two $project stages,

db.collection.aggregate([
  { $match: { server: "strong" } },
  {
    $project: {
      events: {
        $filter: {
          input: "$events",
          cond: { $eq: ["$$this.eventType", "log"] }
        }
      }
    }
  },
  {
    $project: {
      total: {
        visitor: "$events.visitorInfo.visitorId",
        uniquevisitor: {
          $setUnion: "$events.visitorInfo.visitorId"
        }
      }
    }
  }
])

Playground

over 4 years ago · Santiago Trujillo 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