我想在我的模態中對一組物件進行排序,唯一的方法(如我所見)如下:
...
const notifications = await Notification
.aggregate([
{$match: {to: userId}},
{$unwind: '$messages'},
{$sort: {'messages.createdAt':-1}},
{$group: {
_id: '$_id',
createdAt: {$first: '$createdAt'},
messages: {$push: '$messages'},
}}
])
...
但是,我想知道是否還有其他方法可以做到這一點。似乎我必須做這么多操作,即使我想要的只是對陣列進行排序(例如,如果我真的要更改有關資料的任何內容但我沒有更改,那么分組將是有意義的)。我發現的唯一其他方法是:
const notifications = await Notification.findOne({to: userId}).sort({'messages.createdAt': -1})
但這并沒有按降序對我的陣列進行排序,基本上什么都不做。
const notificationSchema = new mongoose.Schema({
to: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
messages: [{
title: {
type: String,
required: true
},
body: {
type: String
},
isRead: {
type: Boolean,
default: false
},
createdAt: {
type: Date,
default: new Date()
}
}, ]
},{timestamps: true});
uj5u.com熱心網友回復:
如果您有 MongoDB 5.2 或更高版本,則可以使用$sortArray運算子。否則,您可以通過展開和分組的路徑。或者您可以修改您的更新操作,Notification model以便它已經按訊息按createdAt降序對訊息進行排序,并且您不必在使用find方法獲取通知時執行排序。像這樣的東西:
db.collection.update({
"notification": "Hello"
},
{
"$push": {
messages: {
"$each": [
{
id: "4"
}
],
"$sort": {
id: -1
}
}
}
})
游樂場鏈接。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/525890.html
