2011-08-07 34 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);