2011-08-07 4 views
0

私はmap/reduceを試したことがありません。mongodb動物の中で最も古いものを取得map/reduce

どのようにして各動物の最も古い動物を得ることができますか?

私のデータは、このようなものです:私はノードMongoDBのネイティブ使用しています

[ 
{ 
    "cateory": "animal", 
    "type": "cat", 
    "age": 4, 
    "id": "a" 
}, 
{ 
    "cateory": "animal", 
    "type": "bird", 
    "age": 3, 
    "id": "b" 
}, 
{ 
    "cateory": "animal", 
    "type": "cat", 
    "age": 7 
    "id": "c" 
}, 
{ 
    "cateory": "animal", 
    "type": "bird", 
    "age": 4, 
    "id": "d" 
}, 
{ 
    "cateory": "animal", 
    "type": "cat", 
    "age": 8, 
    "id": "e" 
}, 
{ 
    "cateory": "company", 
    "type": "Internet", 
    "age": 5, 
    "id": "Facebook" 
} 
] 

。ありがとう!

map = function() { 
    emit({type: this.type}, {age: this.age}); 
} 

と機能を削減:

+0

あなたはMongoDBのでマングースを使用している場合は、ここにマップ/リダクションを実装する方法があります。https://gist.github.com/1123688 – Madhusudhan

答えて

3

あなたのマップ機能は、次のようなものになるはずです

reduce = function(key, values) { 
    maxAge = 0; 
    values.forEach(function(v) { 
    if (maxAge < v['age']) { 
     maxAge = v['age']; 
    } 
    }); 

    return {age: maxAge}; 
} 
+0

? – Harry

+0

this.category == 'animal' – Steve

+0

また、map-reduceコマンドはフィルタリングに使用できる 'query'パラメータを受け入れます。 'type'にインデックスがある場合、' query'パラメータはあなたがいくつかのドキュメント上で 'map()'を実行するのを防ぎます。 –

0

をそれは非常に単純です:

collection.find({type : 'animal'}).sort({animal: -1}).limit(1); 
関連する問題