簡體   English   中英

Mongodb 聚合不同,平均和總和與兩個集合之間的分組

[英]Mongodb aggregation distinct, average and sum with group by between two collection

我有這樣的數據的用戶集合

{
    "_id" : ObjectId("5da594c15324fec81d000027"),
    "password" : "******",
    "activation" : "Active",
    "userType" : "Author",
    "email" : "something@gmail.com",
    "name" : "Something",
    "profilePicture" : "profile_pictures/5da594c15324fec81d0000271607094354423image.png",
    "__v" : 0
}

另一方面,用戶日志有這樣的數據

{
    "_id" : ObjectId("5fcb7bb4485c34a41900002b"),
    "duration" : 2.54,
    "page" : 1,
    "activityDetails" : "Viewed Page for seconds",
    "contentType" : "article",
    "activityType" : "articlePageStayTime",
    "label" : 3,
    "bookId" : ObjectId("5f93e2cc74153f8c1800003f"),
    "ipAddress" : "::1",
    "creator" : ObjectId("5da594c15324fec81d000027"),
    "created" : ISODate("2020-12-05T12:23:16.867Z"),
    "__v" : 0
}

我想做的相當於這個 sql 查詢

SELECT name,count(page),sum(duration),avg(DISTINCT(label)),COUNT(DISTINCT(bookId)) FROM users JOIN userlogs ON users._id=userlogs.creator where userlogs.activityType<>"articleListeningTime" group by users._id.

我可以進行正常group by sum匯總。但是如何用這個來做avg distinctcount distinct 我正在使用 mongodb 版本 3.2

我認為這不需要$group階段,您可以使用$setUnion$size$avg運算符,

  • $lookupuserlogs集合
  • $project顯示必填字段,並根據您的條件過濾userlogs
  • $projectuserlogs中獲取統計信息
    • 使用$size獲取總日志數
    • 使用$sum獲取總持續時間總和
    • 使用$setUnion$avg獲取唯一 label 的平均值
    • 使用$serUnion$size獲取唯一bookId的計數
db.users.aggregate([
  {
    $lookup: {
      from: "userlogs",
      localField: "_id",
      foreignField: "creator",
      as: "userlogs"
    }
  },
  {
    $project: {
      name: 1,
      userlogs: {
        $filter: {
          input: "$userlogs",
          as: "u",
          cond: { $ne: ["$$u.activityType", "articleListeningTime"] }
        }
      }
    }
  },
  {
    $project: {
      name: 1,
      totalCount: { $size: "$userlogs" },
      durationSum: { $sum: "$userlogs.duration" },
      labelAvg: { $avg: { $setUnion: "$userlogs.label" } },
      bookIdCount: { $size: { $setUnion: "$userlogs.bookId" } }
    }
  }
])

操場

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM