多个模式的嵌套查询

时间:2019-05-21 01:17:07

标签: node.js mongodb express mongodb-query

我有两种模式:用户和请求

在请求模式中,我基本上具有诸如eventId,userId,status等的字段。

在用户模式中,有关于用户的课程信息,包括userId,名字,姓氏等。

我要检索的是请求最多的5个用户信息,其中大多数请求标记为“完成”。

所以我首先尝试查询状态为“完成”的请求模式

从这个过滤的请求中,我想我必须计算重复的userId的数量并返回前5个userId。

最后一步应该使用该userId从用户架构中获取用户信息。

我得到了第一个查询,但我无法提出其余查询。

这里有个例子

用户架构:

   _id
   firstName
   lastName

请求架构

 _id
 userId
 ownerId
 status

因此,每次用户创建请求时,都会用用户ID填充userId。

说user1有200个状态为完成的请求, 用户2有100 用户3有50 使用者4有25 用户5有10 用户6有5

我要打印请求完成前5名的用户的名字和姓氏

在这种情况下,应依次为用户1,用户2,用户3,用户4,用户5。

1 个答案:

答案 0 :(得分:0)

这可以使用MongoDB Aggregation

完成
db.requests.aggregate([
  {
    $group: { // group the same users together, count the requests
      _id: '$userId', count: { $sum: 1 }
    }
  }, 
  {
    $lookup: { // "join" the previous results with the user documents
      from: 'users',localField: 'userId', foreignField: '_id', as: 'user' }
    }
  },
  {
    $unwind: '$user' // unwind the previous results, which is an array
  },
  {
    $sort: { count: -1 } // sort by count field descending
  }
])

您的结果将如下所示

[
  { _id: 'user1_id', count: 200, user: { /* user1 document */ } },
  { _id: 'user2_id', count: 100, user: { /* user2 document */ } },
  /* ... */
]