2016-02-16 12:10
浏览 68

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() { 
$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


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


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



    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.

    点赞 打赏 评论

相关推荐 更多相似问题