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

238
Vistas
Mongo $expr return when delta of 2 fields exceeds 20%

This will return docs where field1 is greater that field2

collection.find( { $expr: { $gt: [ "$field1" , "$field2" ] } } )

I want to get documents where difference between field1 and field2 is greater or less than 20. Can that be done?

something like this.

{
  match: {
    $expr: {
      {
        $expr: {
          $gt: [
            $subtract: ["$field1", "$field2"], 20
          ]
        }
      }
    }
  }
}

not looking for an aggregation solution

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

0

Yes, you can just use a similar query to what you're already doing, you just have to check both ways field1 - field2 > 20 or field2 - field1 > 20.

You can easily achieve this using $abs (absolute(field1 - field2) > 20), like so:

db.collection.find({
  $expr: {
    $gt: [
      {
        $abs: {
          $subtract: [
            "$field1",
            "$field2"
          ]
        }
      },
      20
    ]
  }
})

Mongo Playground

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