【问题标题】:Get mutual followers in mongoose在猫鼬中获得共同的追随者
【发布时间】:2020-06-30 03:00:11
【问题描述】:

我想获得相互(因此从所有用户中,我拥有最多共享关注者的用户(我们都关注同一个用户)按该计数排序)。来自我的数据库方案 (mongoDB) 的关注者,具有聚合功能。

用户方案:

let User = new mongoose.Schema({
uid: {
    type: String,
    require: true,
    unique: true
},
    followers: [String],
    following: [String]
})

followers/following 是一组 UID

我试过了:

let me = await User.findOne({uid: uid})
if (me) {
    console.log(me.followers)
    let mutual = await User.aggregate([
        // Match documents that contain the elements
        { "$match": { 
            "followers": { "$in": me.followers }
        }},

        // // De-normalize the array field content
        { "$unwind": "$followers" },

        // Match just the elements you want
        { "$match": { 
            "followers": { "$in": me.followers }
        }},

        // Count by the element as a key
        { "$group": {
            "_id": "$name",  
            "mutual": { "$sum":  1}
        }}
    ])
    if (mutual) {
        console.log('mutual', mutual)
    }
}

但这并没有给出正确的计数

【问题讨论】:

  • 看起来该查询将找到所有关注原始uid 的人也关注的人。通过“共同关注者”,您的意思是要找到所有关注 uiduid 也关注的人?或者您是否正在寻找也关注uid 关注的人的人?
  • 问题不完整。你能定义一下你所说的相互吗?

标签: node.js mongodb mongoose


【解决方案1】:

您可以使用$filter$size 而不是展开每个人的关注者。您也可以使用 $lookup 而不是 2 个客户端查询来执行此操作。

以下管道中的阶段:

  • $match 有问题的用户
  • $lookup 检索所有具有共同追随者的用户,并将它们放入 matched 数组中
  • $unwind 匹配的数组以分别考虑每个用户
  • $match - 因为有问题的用户也将被匹配为具有匹配的追随者,所以消除这个“自我”条目
  • $project 消除了除其他人的 uid 之外的所有字段,对于 commonFollowers:
    • $filter 迭代每个人 followers 数组,只保留那些与相关用户匹配的条目
    • $size 返回剩余元素个数
[
  {"$match": {"uid": uid}},
  {
    "$lookup": {
      "from": "User",
      "localField": "followers",
      "foreignField": "followers",
      "as": "matched"
  }},
  {"$unwind": "$matched"},
  {"$match": {"$expr": {"$ne": ["$matched.uid", "$uid"]}}},
  {"$project": {
      "_id": 0,
      "uid": "$matched.uid",
      "commonFollowers": {
        "$size": {
          "$filter": {
            "input": "$matched.followers",
            "cond": {
              "$in": [
                "$$this",
                "$followers"
              ]
  }}}}}},
  {"$sort": {"commonFollowers": -1}}
])

【讨论】:

  • 你先生是个传奇!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-28
  • 1970-01-01
  • 1970-01-01
  • 2019-07-03
  • 1970-01-01
  • 1970-01-01
  • 2012-05-21
相关资源
最近更新 更多