2016-03-03 47 views
1

我有對象的數組創建多個動態物體的NodeJS查詢MongoDB的

[ 
    { 
    userId: '541c83d89ff44f767a23c546', 
    emailArray: [ 
     '[email protected]', 
     '[email protected]', 
     '[email protected]', 
     '[email protected]' 
    ] 
    }, 
    { 
    userId: '56bd6bf220591a124001d178', 
    emailArray:[ 
     '[email protected]', 
     '[email protected]' 
     '[email protected]' 
    ] 
    } 
] 

併爲每個用戶id我想創建MongoDB的查詢對象,如下面

var q1 = { $and: [ {userId:userId1}, {"interactions.emailId": {$in:emailArray1} 
var q2 = { $and: [ {userId:userId2}, {"interactions.emailId": {$in:emailArray2} 
var q3 = { $and: [ {userId:userId3}, {"interactions.emailId": {$in:emailArray3} 
..... 
var qn = { $and: [ {userId:userId(n)}, {"interactions.emailId": {$in:emailArray(n)} 

其中

userId1 = 541c83d89ff44f767a23c546和userId2 = 56bd6bf220591a124001d178

emailArray1 = [ 
    '[email protected]', 
    '[email protected]', 
    '[email protected]', 
    '[email protected]' 
] 

emailaray2 = [ 
    '[email protected]', 
    '[email protected]' 
    '[email protected]' 
] 

等等。

然後在最後一個最終查詢對象

var queryFinal = { $or: [ q1, q2,q3......qn] } 

我怎麼去呢?

+0

你到底是想通過這樣做是爲了實現什麼? –

+0

還有一件事,在每個查詢中,你不需要'$和'。除此之外,我不明白你想在這裏實現什麼。你能解釋一下嗎? –

+1

我會喂這個queryFinal從集合中獲取一些值。 –

回答

2

只需使用常規的JavaScript:

var data = [ 
    { userId: '541c83d89ff44f767a23c546', 
    emailArray: 
     [ '[email protected]', 
      '[email protected]', 
      '[email protected]', 
      '[email protected]' ] 
    }, 
    { userId: '56bd6bf220591a124001d178', 
    emailArray: 
     [ '[email protected]', 
      '[email protected]', 
      '[email protected]' ] 
    } 
]; 

var queryFinal = { "$or": data.map(function(el) { 
    el["interactions.emailId"] = { "$in": el.emailArray }; 
    delete el.emailArray; 
    return el; 
}) }; 

所有 MongoDB的查詢參數已經是「AND」條件,因此你不需要$and在大多數情況下進行明確說明。

產地:

{ 
     "$or" : [ 
       { 
         "userId" : "541c83d89ff44f767a23c546", 
         "interactions.emailId" : { 
           "$in" : [ 
             "[email protected]", 
             "[email protected]", 
             "[email protected]", 
             "[email protected]" 
           ] 
         } 
       }, 
       { 
         "userId" : "56bd6bf220591a124001d178", 
         "interactions.emailId" : { 
           "$in" : [ 
             "[email protected]", 
             "[email protected]", 
             "[email protected]" 
           ] 
         } 
       } 
     ] 
}