按数组中的最后一项排序



我正试图按数组中的最后一项对其进行排序。这样我就可以按最近一年对这个人进行分类。

这是我用来返回结果的函数。

router.get('/', (req, res) => {
const errors = {};
Person
.find()
.limit(pagingLimit)
.sort(
{year:[0]}
)
.then(people => {
if (!people) {
errors.noprofile = 'There are no profiles';
res.status(404).json(errors);
}
return res.json(people)
})
.catch(err => res.status(404).json({
nopeoplefound: 'No people found'
}));
});

这是我用来排序的项目的一个例子。

{
"first_name": "James",
"last_name": "Smith",
"years": [
{
"year": 2016,
"sector": "Produce",
"job_title": "Coroner"
},
{
"year": 2017,
"sector": "Produce",
"job_title": "Senior Coroner"
}
]
}

您可以通过聚合$unwind年,然后按years: -1:排序

Person.aggregate([
{ $unwind: "$years" },
{ $sort: { years: -1 }}
]).exec()
.then(result => ...)

看到它在这里工作

最新更新