我所拥有的只是一个用户 ID 和此查询:
return gamelog.find({userid: userid).then(function (response) {
return response;
});
具有以下模型:
new Schema({
userid : String,
ip: String,
});
结果至少会给我一个或多个IP。然后我需要查询这些 IP,以检查是否有任何其他用户访问过该 IP 地址。
如何修改此查询,以便从这些 IP 之一获取具有该用户 ID 的所有 IP 或任何用户 ID?
理想的结果是所有用户 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"
}
最佳答案
您可以尝试以下聚合。
下面的查询将过滤“userid”的所有文档,后跟 $group
以获取“ips”的集合,并加入 $lookup
以引入所有用户与查询用户共享相同的 ip。
$unwind
其他用户的文档和 $group
其他用户的 id 并收集 ip,然后是最终组以获取用户 id 和 ip 的集合。
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"
}
}
}
}
])
关于javascript - Mongoose 从用户 ID 或基于 ip 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46818528/