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

426
Views
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 answers
Answer question

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 Report

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 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!