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

211
Vistas
What is the most efficient way to make a calculation within thousands of mongodb documents?

I have a mongo collection. My collection can be considered like this:

{
    "kwId" : "123445",
    "p1": "15"
    "p2": "25",
    "date": "2017-01-28"
}

{
    "kwId" : "123446",
    "p1": "25"
    "p2": "30",
    "date": "2017-01-28"
}

{
    "kwId" : "123445",
    "p1": "35"
    "p2": "40",
    "date": "2017-01-27"
}

{
    "kwId" : "123446",
    "p1": "30"
    "p2": "50",
    "date": "2017-01-27"
}

For each date, I have around 44k documents. Let's say, I want to find differences of p1 and p2 values for documents having same kwId but different date such as 2017-01-28 and 2017-01-27. Example result:

{
    "kwId" : "123445",
    "p1": "20"
    "p2": "15",
}

{
    "kwId" : "123446",
    "p1": "5"
    "p2": "20",
}

What is the most efficient way to do that? I'm using PHP and what I've tried is, retrieve all the documents for given dates and calculate the difference in PHP. It was pretty slow.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

I realized that the right way is to make the calculations with PHP. First, I've changed the structure. I made both kwId and date the id. The are 2 reasons for that.

  1. kwId and date both makes documents unique.
  2. I'm querying the documents by both kwId and date. So they must be indexed to speed up the process.

    { "id": { "kwId": 123445, "date": "2017-01-28" }, "p1": "15", "p2": "25" }

In my question I said "I've tried is, retrieve all the documents for given dates and calculate the difference in PHP. It was pretty slow.". It was taking around 50 minutes for process to be completed. After little change in the document structure as I mentioned above, and using binary search instead of php's default search function, now I have to wait just for milliseconds.

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