聚合两个集合并获得最高值

Aggregate on two collections and get highest value

我想知道 post 的浏览量是被浏览次数最多的。下面是一个小例子。

用户:

{
   username: "John"
},
{
   username: "Doe"
}

消息:

{
   title: "Lorem Ipsum!",
   views: 400,
   author: "John"
},
{
   title: "Lorem Ipsum!",
   views: 200,
   author: "John"
},
{
   title: "Lorem Ipsum!",
   views: 100,
   author: "John"
},
{
   title: "Lorem Ipsum!",
   views: 403,
   author: "Doe"
},
{
   title: "Lorem Ipsum!",
   views: 299,
   author: "Doe"
},

我希望每个用户在包含最多消息查看次数的对象上有一个 属性。像这样:

{
   username: "John"
   highest_view: 400
},
{
   username: "Doe"
   highest_view: 403
}

我可以通过遍历和查询每个对象来用代码解决这个问题,但这似乎不是最方便的方法。

查询 1

  • 聚合用户,查找消息
  • $max 从路径 $highest_views.views
  • 中保留数组的最大值

*$max 是累加器,但也适用于数组

Test code here

users.aggregate(
[{"$lookup": 
    {"from": "Messages",
      "localField": "username",
      "foreignField": "author",
      "as": "highest_views"}},
 {"$set": {"highest_views": {"$max": "$highest_views.views"}}}])

查询2

  • 这样更好,但有点复杂
  • 如果你有大 collections 我想买这个
  • $lookup 带管道,分组以获得最大观看次数
  • 修复结构以获得预期的输出

Test code here

users.aggregate(
[{"$lookup": 
    {"from": "messages",
      "let": {"username": "$username"},
      "pipeline": 
      [{"$match": {"$expr": {"$eq": ["$$username", "$author"]}}},
        {"$group": {"_id": null, "highest_views": {"$max": "$views"}}}],
      "as": "highest_views"}},
  {"$set": 
    {"highest_views": 
      {"$arrayElemAt": ["$highest_views.highest_views", 0]}}}])