我是NodeJS和MongoDB的新手,当我想使用Mongoose使用Sort()执行Find()查询时遇到一个问题。
我想按通知日期对搜索结果进行排序,但它不起作用
这是我的查询
UsersNotifications
.find({user_id: new ObjectId(req.user._id)})
.sort({'notifications.date': -1})
.select('notifications').exec().then(usersNotifications => {
res.locals.usersNotifications = usersNotifications;
});
这是我的模特:
谢谢您的帮助!
答案 0 :(得分:1)
Afaik您无法按嵌套对象排序,但是可以unwind notifications
数组,应用降序排序并重新组合结果。像这样:
.aggregate([
{ $match: { _id: new ObjectId(req.user._id) }},
{ $unwind: '$notifications' },
{ $sort: { 'notifications.date': -1 }},
{ $group: { _id: '$_id', notifications: { $push: '$notifications'}}}])