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

113
Views
Encuentre dónde la propiedad del objeto en la matriz es más grande que la propiedad en otro objeto

Trato de encontrar documentos donde la tasa de propiedad en el objeto es mayor que la tasa de propiedad en otro objeto (ambos están en la misma matriz)

Documento de ejemplo:

 { "rates": [ { "name": "x", "rate": 5 }, { "name": "y", "rate": 4 } ] }

Así es como lo intenté:

 db.ratesCollection.find({ $where: {"rates": { $elemMatch: {name: "x", "rate"}}} > {"rates": { $elemMatch: {name: "y", "rate"}}} }).pretty()

El problema es que no sé cómo comparar valores cuando primero necesito encontrar un objeto en una matriz.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Puede usar $reduce para procesar la matriz y obtener x_rate y y_rate . Después de eso, compare los 2 valores para obtener el resultado.

 db.collection.aggregate([ { "$addFields": { "x_rate": { "$reduce": { "input": "$rates", "initialValue": null, "in": { $cond: [ { $eq: [ "$$this.name", "x" ] }, "$$this.rate", "$$value" ] } } }, "y_rate": { "$reduce": { "input": "$rates", "initialValue": null, "in": { $cond: [ { $eq: [ "$$this.name", "y" ] }, "$$this.rate", "$$value" ] } } } } }, { $match: { $expr: { $gt: [ "$x_rate", "$y_rate" ] } } }, { "$project": { x_rate: false, y_rate: false } } ])

Aquí está el parque infantil de Mongo para su referencia.

over 4 years ago · Santiago Trujillo Report

0

Consulta

  • x>y <=> xy > 0
  • reducir para encontrar el xy y comprobar si es mayor que 0
  • value=0 si encontramos x sumamos si encontramos y restamos, de lo contrario mantenemos el valor como está

Código de prueba aquí

 aggregate( [{"$match": {"$expr": {"$gt": [{"$reduce": {"input":"$rates", "initialValue":0, "in": {"$switch": {"branches": [{"case":{"$eq":["$$this.name", "x"]}, "then":{"$add":["$$value", "$$this.rate"]}}, {"case":{"$eq":["$$this.name", "y"]}, "then":{"$subtract":["$$value", "$$this.rate"]}}], "default":"$$value"}}}}, 0]}}}])
over 4 years ago · Santiago Trujillo 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!