所以我试图通过它的插入日期排序用户的通知数组(我想要最新的一个在顶部),但它似乎不工作,我错过了什么?
下面是data的模板:
{
_id: "628ceeae3df06d49419f0bb4",
name: "John",
notifications: [
{_id: "someIdA", details: "xyz", dateTime: "1653321337762"},
{_id: "someIdB", details: "jkl", dateTime: "1653321337762"}
{_id: "someIdC", details: "abc", dateTime: "1653321321323"}
{_id: "someIdD", details: "lmn", dateTime: "1653123412341"}
]
}
和聚合管道,我正在尝试:
const foundUser = await users.aggregate([
{
$match: {
_id: mongoose.Types.ObjectId(userId)
}
},
{
$project: {
notifications: 1,
_id: 0
}
},
{
$sort: {
_id: -1
}
}
])
首先展开通知数组,按通知DateTime键对文档进行排序,然后按用户分组。
这是mongo shell查询:
db.collection.aggregate([
{
$match: {
_id: "628ceeae3df06d49419f0bb4"
}
},
{
$unwind: "$notifications"
},
{
$sort: {
"notifications.dateTime": -1
}
},
{
$group: {
_id: "$_id",
notifications: {
$push: "$notifications"
}
}
},
{
"$project": {
"notifications": 1,
"_id": 0
}
}
])
这里,是工作链接Mongodb Playground