2017-10-18 104 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