2017-08-10 130 views
0

我需要從mongoDB獲取每個選定文檔的數組的所有唯一值(使用meteorJS,這必須在服務器端完成)。MongoDB/JS:如何獲得數組字段的所有唯一字符串值

數據結構

{ 
    _id: 'Wt7gSvxSPbRw46KHK', 
    parent: 'doxCi4MSNmFJE43EH', 
    target: [ 'ejiSooMx6czQxzWmW', 'Q297RZEYKJdWWRyTJ' ] 
} 

這是我的查詢和target與字符串元素的數組。

查詢

Collection.find(
    { parent: parent, target: { $exists: true } }, 
    { field: { target: 1 } } 
).map(doc => { return doc.target }) 

現在我的這個查詢的結果是這樣的:

[ 
    [ 'Q297RZEYKJdWWRyTJ' ], 
    [ 'Q297RZEYKJdWWRyTJ', 'ejiSooMx6czQxzWmW' ], 
    [ 'ejiSooMx6czQxzWmW', 'Q297RZEYKJdWWRyTJ' ], 
    [ 'ejiSooMx6czQxzWmW' ] 
] 

我的第一個問題是對數組的內容映射不是陣列本身,應該看起來像這樣:

[ 
    'Q297RZEYKJdWWRyTJ', 
    'Q297RZEYKJdWWRyTJ', 'ejiSooMx6czQxzWmW', 
    'ejiSooMx6czQxzWmW', 'Q297RZEYKJdWWRyTJ', 
    'ejiSooMx6czQxzWmW' 
] 

個至少結果應具有唯一值:

[ 'Q297RZEYKJdWWRyTJ', 'ejiSooMx6czQxzWmW' ] 
+0

你可以添加一個樣本文檔?從那個集合?回答你的問題將會非常有幫助。 –

+0

向帖子中添加了數據結構 – user3142695

回答

0

您可以使用.concat().apply().reduce()

var uniqArray = [].concat.apply([], 
    Collection.find(
    { parent: parent, target: { $exists: true } }, 
    { field: { target: 1 } } 
).map(doc => doc.target) 
).reduce((acc,curr) => (acc.indexOf(curr) === -1) ? acc.concat(curr) : acc,[]) 

退貨:

[ 
    "Q297RZEYKJdWWRyTJ", 
    "ejiSooMx6czQxzWmW" 
] 

這就是你要求的。

或者你應該能夠使用.rawCollection().distinct()

var uniqArray = Collection.rawCollection().distinct("target",{ 
    parent: parent, target: { "$exists": true } 
}) 
+0

@ user3142695它適用於我。基本上,如果我只是用當前輸出中的「數組數組」來替換'Collection.find()'語句,那麼所需的輸出就是我所得到的。 –

0

您可以使用過濾器獲得獨特的數組元素

var unique = array.filter(function(value, index, self) { 
    return self.indexOf(value) === index; 
}); 
0

您可以使用underscore.js乾淨解決這個問題,它已經包含在meteor

_.chain(Collection.find({ parent: parent, target: { $exists: true } }).fetch()) 
.pluck('target') 
.flatten() 
.value(); 
相關問題