Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to make group by query in MongoDb

    • 0
    • 1
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 708
    Comment on it

    Making a group by query in traditional database like MySQL,MySQL etc in quite easy but when its come to NoSQL like MongoDb we have to twist it a bit to get result we want :

    There are two ways in which you can do group by in MongoDb :

    a) Using group function of MongoDb but this particular function have its own limitation of not able to sort result while grouping them:

    $keys = array("attempt_date" => 1);
    $initial = array("items" => array());
    $reduce = "function (obj, prev) { prev.items.push(obj); }";
    $start = "2014-01-25";
    $end ="2014-01-28";
    $condition = array('condition' => array("attempt_date" => array('$gte' => $start, '$lte' => $end)));
    $result = $collection->group($keys, $initial, $reduce,$condition);

    b) Using more advanced aggregate function which help you achieve group by and also allow you to short result according to user requirement. But while using aggregate function user have to mention fields they need in the result , it is not able to add the entire object of collection as group by function is able to do.

    $result = $collection->aggregate(array(
                        array('$match' =>array('attempt_date' => array('$gte' => $start, '$lte' => $end))),
                        array('$group' => array(
                            '_id' => '$attempt_date',
                            'items' => array('$push' => array('_id'=>'$_id','user_id'=>'$user_id',
                                'worksheet_id'=>'$worksheet_id','time_taken'=>'$time_taken','attempt_date'=>'$attempt_date'
                                ,'completion_date'=>'$completion_date','correct_question_count'=>'$correct_question_count',
                                'wrong_question_count'=>'$wrong_question_count','status'=>'$status'
                                ))
                        )),
                        array('$sort' => array('_id'=>-1))     
                    )
               ); 

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: