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?
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.
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")] }
]}
}}
]
}
}
}
]);