2017-10-18 101 views
0

我只有一个用户名和此查询:猫鼬查询基于IPS

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

以下模型:

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

}); 

结果将至少给我一个或多个IP。然后我需要查询这些IP来检查是否有任何其他用户在该IP地址上。

我该如何修改此查询,以便从其中一个IP获得具有该userid或任何userid的所有IP?

理想的结果将导致所有用户的IP地址,以及所有其他用户都在用户标识所在的任何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" 
} 

回答

1

你可以试试下面聚集。

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

$unwind$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" 
     } 
     } 
    } 
    } 
]) 
+0

变量ipuser会保存什么? 原因,目前尚未定义。 – maria

+0

对不起,应该是ipuserf。更新了答案。 – Veeram

+0

是的,试过了。但是,然后日志中的每一行都获取用户属性。我该如何修改答案,只让我从该用户和使用它的用户那里获得地址? – maria