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

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

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 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