2011-08-07 27 views
0

我從未嘗試過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" 
} 
] 

我使用節點MongoDB的母語。謝謝!

+0

如果您使用的是貓鼬用MongoDB的,這裏是如何實現地圖/減少https://gist.github.com/1123688 – Madhusudhan

回答

3

你的地圖功能應該是這個樣子:

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

而減少功能:

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

    return {age: maxAge}; 
} 
+0

我如何確保它只顯示動物? – Harry

+0

只在地圖函數中發射一些東西if this.category =='animal' – Steve

+0

此外,map-reduce命令接受可用於過濾的「query」參數。如果你在'type'有一個索引,那麼'query'參數將會讓你免於在幾個文檔上運行'map()'。 –

0

這很簡單:

collection.find({type : 'animal'}).sort({animal: -1}).limit(1); 
相關問題