2016-07-28 58 views
0

Goodmorning在不同記錄中匹配2個字段Mongoose

我想匹配數據集上的特定字段。該數據集包含像記錄:

{ 
    "token" : "17e0d95f2e2112443cfb09970ae9140e", 
    "answers" : { 
     "Yourname" : "Marco", 
     "youremail" : "[email protected]", 
     "recemail" : "[email protected]" 
    } 
}, 


{ 
    "token" : "cf5ae65b05249dc6b2a0c99c4cf9688e", 
    "answers" : { 
     "yourname" : "Sonja", 
     "youremail" : "[email protected]", 
     "recemail" : "[email protected]" 
    } 
} 

在這種情況下,它應該符合兩個,因爲recemail(收件人電子郵件)匹配別人的電子郵件地址。反之亦然。 我想找到的是如何找到這兩個記錄(在更多的這些匹配更大的數據集)。

因此,Marco的recemail應該找到Sonja的youremail,然後這兩個匹配應該保存到另一個集合中,但這不是重要的部分。

希望有人能幫助我解決此問題 謝謝!

+0

你需要'X.youremail == Y.recemail && X.recemail == Y.youremail'?或者只是'X.youremail == Y.recemail || X.recemail == Y.youremail'? – Arnauld

+0

喜歡這個。 '''X.recemail == Y.youremail && Y.recemail == X.youremail''' – Marco

回答

1

以下代碼將返回一個2入口數組的數組。每個2入口數組由發件人電子郵件和收件人電子郵件組成。每一對只會出現一次。換句話說,你會得到["[email protected]", "[email protected]"],但不是["[email protected]", "[email protected]"]

var list = [{ 
 
    "token" : "17e0d95f2e2112443cfb09970ae9140e", 
 
    "answers" : { 
 
     "Yourname" : "Marco", 
 
     "youremail": "[email protected]", 
 
     "recemail" : "[email protected]" } 
 
    }, { 
 
    "token" : "cf5ae65b05249dc6b2a0c99c4cf9688e", 
 
    "answers" : { 
 
     "yourname" : "Sonja", 
 
     "youremail": "[email protected]", 
 
     "recemail" : "[email protected]" } 
 
    }, { 
 
    "token" : "fe2c2740e083dfe02cc7e96520a0e079", 
 
    "answers" : { 
 
     "yourname" : "Joe", 
 
     "youremail": "[email protected]", 
 
     "recemail" : "[email protected]" } 
 
    } 
 
]; 
 

 
var res = [], sz = list.length; 
 

 
list.forEach(function(obj, pos) { 
 
    for(var i = pos + 1; i < sz; i++) { 
 
    if(
 
     list[i].answers.youremail == obj.answers.recemail && 
 
     list[i].answers.recemail == obj.answers.youremail 
 
    ) { 
 
     res.push([ obj.answers.youremail, obj.answers.recemail ]); 
 
    } 
 
    } 
 
}); 
 
console.log(res);

+0

非常感謝,但問題與Mongoose查詢有關。這有效,我可以獲取所有數據,然後在節點上獲取我想要的數據,但這是我最初需要的MongoDB查詢。如果我沒有得到滿意的答案,我一定會隨着你的回答而去。 :) – Marco

+0

@Marco好啊。感謝您接受了這一點,並感到抱歉,因爲無法爲您提供更多幫助。 – Arnauld

相關問題