doudou5421 2016-02-16 12:10
浏览 72
已采纳

MongoDB / PHP - MapReduce最大值

I used to group on mongoDB via PHP to get the max date of my items. As i have too many items (more than 10 000), i read i must use MapReduce.

Here's my past group function :

$keys = array('ItemDate'=> true);       
$initial = array('myLastDate' => 0);        
$reduce = "function(obj, prev) { 
  if (myLastDate < obj.ItemDate) { 
    myLastDate = ItemDate; 
  } 
}";         
$conds = array( 'ItemID' => (int) $id );

$results = $db->items->group($keys, $initial, $reduce,
array('condition'=> $conds ) );

I've tried something but seems not to work ...

$map = new MongoCode("function() { 
  emit(this.ItemID,this.ItemDate);
}");        
$reduce = new MongoCode("function(obj, prev) { 
  if(prev.myLastDate < obj.ItemDate) { 
    prev.myLastDate = obj.ItemDate; 
  }
}");

$items = $db->command(array(
            "mapreduce" => "items", 
            "map" => $map,
            "reduce" => $reduce,
            "query" => array("ItemID" =>  $id);

$results = $db->selectCollection($items['result'])->find();

Can you please help ?

  • 写回答

1条回答 默认 最新

  • doucheyi1347 2016-02-16 12:35
    关注

    Solution

    You don't need to use map/reduce for that. Provided your date field contains an ISODate, a simple query does the trick:

    db.yourColl.find({},{_id:0,ItemDate:1}).sort({ItemDate:-1}).limit(1)
    

    In order to have this query done efficiently, you need to set an index on ItemDate

    db.yourColl.createIndex({ItemDate:-1})
    

    Explanation

    The query

    Let us dissect the query. db.yourColl...

    • .find({} The default query
    • ,{_id:0,ItemDate:1} We want only ItemDate to be returned. This is called a projection.
    • .sort({ItemDate:-1}) The documents returned should be sorted in descending order on ItemDate, making the document with the newest date the first to be returned.
    • .limit(1) And since we only want the newest, we limit the result set to it.

    The index

    We create the index in descending order, since this is the way you are going to use it. However, if you need to change the default query to something else, the index you create should include all fields you inspect in the query, in the exact order.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 matlab计算中误差
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊