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.

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

报告相同问题?

悬赏问题

  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站