简体   繁体   中英

use match, limit, sort, and lookup together in mongoose query

I have 2 colletcions:

  1. User
  2. Notification

User:

{
  id:1,
  name:ABC
},
{
  id:2,
  name:ABC2
},
{
  id:3,
  name:ABC3
}

Notification:

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

I want to fetch Notifications data with match (read:false), sort(descending order on createdAt), limit(5) and lookup on user collection based on user id in notification data

Query should return:

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

You can try,

  • $match to match your conditions
  • $lookup to join user collection
  • $unwind deconstruct user array because its an array and we need object
  • $project to show required fields
  • $sort by createdAt descending order
  • $limit 5 documents
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM