2014-01-13 123 views
0

在Meteor.js中,我們如何選擇獨特的字段組合?例如,如果我們有:在Meteor.js中選擇具有獨特字段組合的記錄

type color owner 
---- ----- ----- 
animal red  paul 
animal red  jack 
animal blue  paul 
food blue jack 

應該做些什麼來得到以下結果集:

type color 
---- ----- 
animal red 
animal blue 
food blue 

我使用meteor-smart-collections 0.4.0和流星0.7.0.1

回答

0

你如果您準備做fetch(),可以使用下劃線來相當容易地做到這一點,這可能取決於您獲得了多少文檔:

_.uniq(yourCollection.find({}, {fields: {type: 1, color: 1, _id: 0}}).fetch(), function(item) { return item.type+item.color; }); 

唯一的警告是您爲了比較的目的而串接字符串,所以如果存在像{type: 'foo', color: 'bar'}{type: 'foob', color: 'ar'}這樣的對的任何可能性,它將會失敗。在你給出的例子中,這似乎不太可能,但如果你擔心它是一個問題,那麼你只需要改變迭代器函數的結構,以便比連接兩個字段更有想象力。它需要返回一個原始的,但我不認爲它會工作,如果你返回一個對象或數組。

+0

一個更好的函數可能是'function(item){return JSON.stringify ({type:item.type,color:item.color}); }' – sbking

+0

同意,Cuberto! – richsilv

0

我不認爲流星的Minimongo驅動程序包含聚合框架的幫助,但至少有一個問題有suggestions on how to call the underlying MongoDB aggregate command

假設你的數據是這樣的:

db.things.aggregate(
    { $group: { 
     _id: { type: "$type", color: "$color" } 
    }} 
) 

結果會是什麼樣子:

{ 
    "result" : [ 
     { 
      "_id" : { 
       "type" : "food", 
       "color" : "blue" 
      } 
     }, 
     { 
      "_id" : { 
       "type" : "animal", 
       "color" : "blue" 
      } 
     }, 
     { 
      "_id" : { 
       "type" : "animal", 
       "color" : "red" 
      } 
     } 
    ], 
    "ok" : 1 
} 

db.things.insert([ 
    { type: 'animal', color: 'red', owner: 'paul'}, 
    { type: 'animal', color: 'red', owner: 'jack'}, 
    { type: 'animal', color: 'blue', owner: 'paul'}, 
    { type: 'food', color: 'blue', owner: 'jack'} 
]) 

可以使用MongoDB的Aggregation Framework$group operator做在服務器端這個分組

相關問題