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

436
Vistas
MongoDB $sort on $concatArrays

I'm trying to concatenate two nested arrays (using $concatArrays) into one new field. I'd like to sort the output of the concatenation (Model.timeline) by a property that exists in both sets of objects. I can't seem to get it working with $unwind. Here's the query without any sorting:

Model.aggregate([
    {
        $match: {
            'id': id
        }
    },
    {
        $project: {
            id: 1,
            name: 1,
            flagged: 1,
            updatedAt: 1,
            lastEvent: {
                $arrayElemAt: ['$events', -1]
            },
            lastimage: {
                $arrayElemAt: ['$images', -1]
            },
            timeline: {
                $concatArrays: [
                    { $filter: {
                        input: '$events',
                        as: 'event',
                        cond: { $and: [
                            { $gte: ['$$event.timestamp', startAt] },
                            { $lte: ['$$event.timestamp', endAt] }
                        ]}
                    }},
                    { $filter: {
                        input: '$images',
                        as: 'image',
                        cond: { $and: [
                            { $gte: ['$$image.timestamp', startAt] },
                            { $lte: ['$$image.timestamp', endAt] }
                        ]}
                    }}
                ]
            }
        }
    }
]);

Am I missing something obvious?

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

0

You need three pipeline stages after your match and project. First $unwind, then $sort and then re $group. Use the $first operator to retain all the fields.

{
    $undwind : "$timeline",
},
{
    $sort : {"your.sortable.field" : 1}
},
{
    $group : {
        _id : "$_id",
        name : {$first : 1},
        flagged : {$first : 1},
        updatedAt : {$first : 1},
        lastEvent : {$first : 1},
        lastimage : {$first : 1},
        timeline : {$push : "$timeline"}
    }
}

Please note that this will work even when you have more than one document after the match phase. So basically this will sort the elements of an array within each document.

over 4 years ago · Santiago Trujillo Denunciar

0

Your $match and $project aggregation stages worked after I substituted id with _id, and filled in the values for id, startAt and endAt like so:

db.items.aggregate([
     {
        $match: {
            '_id': '58'
        }
    },
    {
        $project: {
            '_id': 1,
            name: 1,
            flagged: 1,
            updatedAt: 1,
            lastEvent: {
                $arrayElemAt: ['$events', -1]
            },
            lastimage: {
                $arrayElemAt: ['$images', -1]
            },
            timeline: {
                $concatArrays: [
                    { $filter: {
                        input: '$events',
                        as: 'event',
                        cond: { $and: [
                            { $gte: ['$$event.timestamp', ISODate("2016-01-19T20:15:31Z")] },
                            { $lte: ['$$event.timestamp', ISODate("2016-12-01T20:15:31Z")] }
                        ]}
                    }},
                    { $filter: {
                        input: '$images',
                        as: 'image',
                        cond: { $and: [
                            { $gte: ['$$image.timestamp', ISODate("2016-01-19T20:15:31Z")] },
                            { $lte: ['$$image.timestamp', ISODate("2016-12-01T20:15:31Z")] }
                        ]}
                    }}
                ]
            }
        }
    }
]);
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