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

351
Views
Agregación de MongoDB, combinando 2 arreglos en modo round-robin

Tengo datos en una colección MongoDB que se parece a esto:

 [ { "_id": 1, "type": "big", "fields": [11, 12, 13], "items": [21, 22, 23] }, { "_id": 2, "type": "small", "fields": [14, 15], "items": [24, 25] }, { "_id": 3, "type": "small", "fields": [], "items": [41, 42] }, { "_id": 4, "type": "small", "fields": [31, 32, 33], "items": [] } ]

Me han encargado devolver datos de acuerdo con un procedimiento como este:

Para cada documento de la colección, obtenga 1 valor de sus fields (si los hay) y 1 valor de sus items (si los hay). Concatene todos los resultados en una sola matriz.

Se podría resumir esto como la selección de datos en forma de "intercambio por turnos" de dos matrices contenidas en cada documento.

¿Cómo lograría esto en una consulta de agregación de MongoDB? Esta lógica no es difícil de implementar en el cliente que se conecta al servidor Mongo, pero me gustaría dejar que Mongo se encargue de la paginación (con $skip y $limit ). Estoy usando MongoDB 4.4.

Los datos resultantes se verían así:

 [ { "value": 11, "type": "field", "fromId": 1 }, { "value": 21, "type": "item", "fromId": 1 }, { "value": 14, "type": "field", "fromId": 2 }, { "value": 24, "type": "item", "fromId": 2 }, { "value": 41, "type": "item", "fromId": 3 }, { "value": 31, "type": "field", "fromId": 4 }, ]
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Si entiendo bien tu pregunta; esto debería ser una tubería viable. Para implementar una funcionalidad aleatoria, simplemente ajustaría el índice pasado a $arrayElemAt

https://mongoplayground.net/p/PPXV6fTSwHP

 db.collection.aggregate([ {$project: { types: [ {type: "field", values: "$fields"}, {type: "item", values: "$items"} ] }}, {$unwind: '$types'}, {$project: { _id: 0, value: {$arrayElemAt: ['$types.values', 0]}, type: '$types.type', fromId: '$_id' }}, {$match: { value: {$exists: true} }} ])

La aleatorización se vería así: https://mongoplayground.net/p/qi1Ud53J6yv

 db.collection.aggregate([ {$project: { types: [ {type: "field", values: "$fields"}, {type: "item", values: "$items"} ] }}, {$unwind: '$types'}, {$project: { _id: 0, value: {$arrayElemAt: [ '$types.values', {$floor: {$multiply: [{$rand: {}}, {$size: '$types.values'}]}} ]}, type: '$types.type', fromId: '$_id' }}, {$match: { value: {$exists: true} }} ])
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!