Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

99
Views
¿Cómo verificar si 2 elementos dentro de una matriz de objetos tienen el mismo valor en mongoDB?

Los datos de la colección de mis users se ven así dentro de mongoDB:

 _id: ObjectId, sports: [ { name: 'cricket', history: [ { from: 10, to: 30 }, { from: 30, to: 30 } ] }, // ... other sports as well ]

Lo que estoy tratando de consultar son todos los usuarios que tienen dentro sports.history un elemento coincidente que satisface esta condición: from === to . (Los usuarios pueden tener varios deportes, cada uno con su propia historia). Estoy tratando de lograr esto dentro de la consulta, no llevar a los usuarios a mi aplicación Express y filtrarlos después.

Cualquier ayuda es muy apreciada. ¡Gracias!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Usando el operador $expr , puede hacer esto usando varios operadores de matriz para consultar la colección. Considere primero aplanar la matriz 2D '$sports.history' con $reduce :

 { $reduce: { input: "$sports.history", initialValue: [], in: { $concatArrays: [ "$$value", "$$this" ] } } }

y filtrando la matriz reducida en la condición dada con $filter

 { $filter: { input: { $reduce: { input: "$sports.history", initialValue: [], in: { $concatArrays: [ "$$value", "$$this" ] } } }, cond: { $eq: ['$$this.from', '$$this.to'] } } }

Verifique la longitud de la matriz resultante de la expresión anterior usando $size :

 { $size: { { $filter: { input: { $reduce: { input: '$sports.history', initialValue: [], in: { $concatArrays: [ '$$value', '$$this' ] } } }, cond: { $eq: ['$$this.from', '$$this.to'] } } } } }

Si la longitud de la matriz filtrada es mayor que cero, entonces el usuario existe:

 { $gt: [ { $size: { $filter: { input: { $reduce: { input: "$sports.history", initialValue: [], in: { $concatArrays: [ "$$value", "$$this" ] } } }, cond: { $eq: ['$$this.from', '$$this.to'] } } } }, 0 ] }

En general, su consulta final debería verse así:

 db.users.find({ $expr: { $gt: [ { $size: { $filter: { input: { $reduce: { input: "$sports.history", initialValue: [], in: { $concatArrays: [ "$$value", "$$this" ] } } }, cond: { $eq: ['$$this.from', '$$this.to'] } } } }, 0 ] } })

Parque infantil Mongo

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!