Skip to content

Instantly share code, notes, and snippets.

@nocodehummel
Last active January 8, 2025 08:57
Show Gist options
  • Select an option

  • Save nocodehummel/ed028b1deafe72508287a14fe81ffb5e to your computer and use it in GitHub Desktop.

Select an option

Save nocodehummel/ed028b1deafe72508287a14fe81ffb5e to your computer and use it in GitHub Desktop.
Mongoose aggregate and unwind
let activities = await Activity.aggregate([
{ $match: filter }, // filter to be applied
{ $lookup: { // populate the instrument(s)
from: 'instruments',
localField: 'instrument',
foreignField: '_id',
as: 'instrument'
}},
{ $unwind: '$instrument'}, // instrument array to object
{ $unwind: '$events' }, // flatten events
{ $sort: { 'events.date': -1 }}
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment