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

239
Views
Comparando objetos dentro de una matriz anidada - mongoDB

En mi base de datos tengo una matriz anidada de elementos dentro de cada documento que contiene elementos, de la siguiente forma:

 elements:[ { "elem_id": 12, items: [ {"i_id": 1, "type": x}, {"i_id": 2, "type": y}, {"i_id": 3, "type": x}] }, { "elem_id": 13, items: [ {"i_id": 4, "type": x}, {"i_id": 5, "type": x}] } ]

Estoy tratando de devolver todos los elementos que tienen elementos de diferentes tipos, lo que significa que solo obtendría:

 { "elem_id": 12, items: [ {"i_id": 1, "type": x}, {"i_id": 2, "type": y}, {"i_id": 3, "type": x}] }

ya que hay artículos de tipo x y de tipo y.

Creo que necesito iterar la matriz de elementos y comparar el tipo de cada elemento de la matriz con los tipos de los elementos anteriores, pero no sé cómo hacerlo en conjunto.

Solo para tener en cuenta: estoy usando Redash, por lo que no puedo incluir ningún JS en la consulta.

¡Gracias por la ayuda!

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Prueba esto:

 db.elements.aggregate([ { $unwind: "$elements" }, { $addFields: { "count": { $size: "$elements.items" }, "uniqueValues": { $reduce: { input: "$elements.items", initialValue: [{ $arrayElemAt: ["$elements.items.type", 0] }], in: { $setUnion: ["$$value", ["$$this.type"]] } } } } }, { $match: { $expr: { $eq: ["$count", { $size: "$uniqueValues" }] } } } ]);

Producción:

 { "_id" : ObjectId("603f8f05bcece4372062bcea"), "elements" : { "elem_id" : 12, "items" : [ { "i_id" : 1, "type" : 1 }, { "i_id" : 2, "type" : 2 }, { "i_id" : 3, "type" : 3 } ] }, "count" : 3, "uniqueValues" : [1, 2, 3] }
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!