【问题标题】:Nested Query for multiple schemas多个模式的嵌套查询
【发布时间】:2019-10-07 08:28:43
【问题描述】:

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

在请求模式中,我基本上有 eventId、userId、status 等字段。

在用户模式中,当然有关于用户的信息,包括用户 ID、名字、姓氏等。

我想做的是检索请求最多的前 5 个用户信息,并将其标记为完成。

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

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

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

我收到了第一个查询,但我无法查询其余的查询。

举个例子

用户架构:

   _id
   firstName
   lastName

请求架构

 _id
 userId
 ownerId
 status

所以每次用户创建请求时,userId都会填写用户Id。

假设 user1 有 200 个状态 = 完成的请求, 用户 2 有 100 用户 3 有 50 用户 4 有 25 用户 5 有 10 用户 6 有 5 个

我想打印前 5 个已完成请求的用户的名字和姓氏,

在这种情况下,它应该依次是用户 1、用户 2、用户 3、用户 4、用户、5。

【问题讨论】:

  • 您能否展示一些示例文档以及您尝试在其上运行的查询?
  • 我已经更新了架构,你可以看看吗?

标签: node.js mongodb express mongodb-query


【解决方案1】:

这可以使用 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 */ } },
  /* ... */
]

【讨论】:

    猜你喜欢
    • 2021-06-29
    • 1970-01-01
    • 1970-01-01
    • 2018-12-10
    • 2021-01-31
    • 1970-01-01
    • 1970-01-01
    • 2018-04-06
    • 1970-01-01
    相关资源
    最近更新 更多