我有2个collections:
用户:
{
id:1,
name:ABC
},
{
id:2,
name:ABC2
},
{
id:3,
name:ABC3
}
通知:
{
id:1,
userId:1,
read:false,
info: 'Notification for user 1'
},{
id:2,
userId:2,
read:false,
info: 'Notification for user 2'
},{
id:3,
userId:3,
read:false,
info: 'Notification for user 3'
}
我想获取具有匹配(read:false),sort(在createdAt上降序),limit(5)和基于通知数据中的用户ID的用户集合查找的Notifications数据
查询应返回:
[{
id:1,
userId:1,
read:false,
info: 'Notification for user 1'
username:ABC
},{
id:2,
userId:2,
read:false,
info: 'Notification for user 2'
username:ABC2
},{
id:3,
userId:3,
read:false,
info: 'Notification for user 3'
username:ABC3
}]
答案 0 :(得分:0)
您可以尝试
$match
以符合您的条件$lookup
加入用户集合$unwind
解构用户数组,因为它是一个数组,我们需要对象$project
以显示必填字段$sort
按createdAt
降序$limit
5个文档db.notification.aggregate([
{ $match: { read: false } },
{
$lookup: {
from: "user",
as: "user",
localField: "userId",
foreignField: "id"
}
},
{ $unwind: "$user" },
{
$project: {
id: 1,
userId: 1,
read: 1,
info: 1,
username: "$user.name"
}
},
{ $sort: { createdAt: -1 } },
{ $limit: 5 }
])