【问题标题】:Mongoose query from userid or based on ips来自用户 ID 或基于 ips 的 Mongoose 查询
【发布时间】:2018-03-30 19:41:41
【问题描述】:

我只有一个用户 ID 和这个查询:

  return gamelog.find({userid: userid).then(function (response) {
                return response;
            });

使用以下型号:

new Schema({
    userid : String,
    ip: String,

});

结果至少会给我一个或多个IP。然后我需要查询这些 IP 以检查是否有其他用户使用该 IP 地址。

如何修改此查询,以便从其中一个 IP 获取具有该用户 ID 或任何用户 ID 的所有 IP?

理想的结果是所有用户 ID 的 IP 地址,以及所有其他用户都在该用户 ID 所在的任何 IP 上。

编辑:

示例文档:

{
time: "1507127113173",
ip:"::1",
others: 0,
url:"/api/gameapi?action=getweapon",
userid:"59d4ef435048380ff4abd683"
}

{
time: "1507127113173",
ip:"::1",
others: 0,
url:"/api/gameapi?action=getweapon",
userid:"59d4ef43504833333333380ff4abd683"
}

【问题讨论】:

    标签: javascript node.js mongodb mongoose nosql


    【解决方案1】:

    您可以尝试以下聚合。

    下面的查询将过滤“userid”的所有文档,后跟$group 以获取“ips”的集合,并加入$lookup 以使所有用户与查询的用户共享相同的ips。

    $unwind 其他用户的文档和$group 在其他用户的 id 上并收集 ips,然后是最终组以获取用户 id 和 ips 的集合。

    db.gamelog.aggregate([
      {
        "$match": {
          "userid": userId
        }
      },
      {
        "$group": {
          "_id": null,
          "ips": {
            "$push": "$ip"
          }
        }
      },
      {
        "$lookup": {
          "from": "gamelog",
          "localField": "ips",
          "foreignField": "ip",
          "as": "otherusers"
        }
      },
      {
        "$unwind": "$otherusers"
      },
      {
        "$match": {
          "otherusers.userid": {
            "$ne": userId
          }
        }
      },
      {
        "$group": {
          "_id": "$otherusers.userid",
          "ips": {
            "$first": "$ips"
          },
          "otheruserips": {
            "$push": "$otherusers.ip"
          }
        }
      },
      {
        "$group": {
          "_id": null,
          "ips": {
            "$first": "$ips"
          },
          "otherusers": {
            "$push": {
              "userid": "$_id",
              "ips": "$otheruserips"
            }
          }
        }
      }
    ])
    

    【讨论】:

    • 变量 ipuser 将持有什么?原因,它目前未定义。
    • 抱歉应该是ipuserf。更新了答案。
    • 是的,试过了。但是随后日志中的每一行都获得了用户属性。我怎样才能修改你的答案,只给我那个用户和使用它的用户的地址?
    • 类似ips的响应:ips数组,其他用户:包含用户和用户匹配的ips的数组(必须与userid相同的ips)
    • 将尽快确认。目前我得到一个空输出。
    猜你喜欢
    • 1970-01-01
    • 2019-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-24
    • 2022-01-25
    • 2019-06-14
    • 1970-01-01
    相关资源
    最近更新 更多