在猫鼬查询中一起使用匹配,限制,排序和查找

时间:2020-08-25 11:39:55

标签: node.js mongodb mongoose

我有2个collections:

  1. 用户
  2. 通知

用户:

{
  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
}]

1 个答案:

答案 0 :(得分:0)

您可以尝试

  • $match以符合您的条件
  • $lookup加入用户集合
  • $unwind解构用户数组,因为它是一个数组,我们需要对象
  • $project以显示必填字段
  • $sortcreatedAt降序
  • $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 }
])

Playground