Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save RahulJyala7/7f08b12c2002774054a34883a432f18e to your computer and use it in GitHub Desktop.
Save RahulJyala7/7f08b12c2002774054a34883a432f18e to your computer and use it in GitHub Desktop.
Mongo query with sorted subDocument
db.getCollection('test').aggregate([{$match: {name: "item6"}},{$unwind: '$slots'}, {$sort: {"slots.date": -1}},
{$group: {_id: '$_id',root: { $mergeObjects: '$$ROOT' }, slots: {$push: '$slots'}}}, { "$limit": 1 }, {
$replaceRoot: {
newRoot: {
$mergeObjects: ['$root', '$$ROOT']
}
}
}, {
$project: {
root: 0
}
}])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment