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

183
Visualizações
MongoDB: Find sets of documents that have same key value

I'm searching a collection based on some conditions:

const orders = Order.find({ status: 'ACTIVE', isInFlux: true  });

Then as I loop through every one of those documents I search Orders again with:

Order.find({ userId: order.userId, status: 'ACTIVE', inFlux: true })

Then I check to see if there are multiple orders belonging to this user that meet these conditions.

Is there a way I can modify my query to get these documents in one shot without having to loop through all of them or possibly an aggregation that would help me?

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

0

Looks like you're just trying to conditionally group orders by userID. This will probably do the trick:

db.collection.aggregate([
  {
    "$group": {
      "_id": "$user",
      "orders": {
        "$push": {
          "$cond": [
            {
              $and: [
                {
                  "$eq": [
                    "$isInFlux",
                    true
                  ]
                },
                {
                  "$eq": [
                    "$status",
                    "active"
                  ]
                }
              ]
            },
            "$$ROOT",
            "$$REMOVE"
          ]
        }
      }
    }
  }
])

Playground: https://mongoplayground.net/p/c8MGdZsjMlJ

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