Aman Gupta Aman Gupta - 7 months ago 7
PHP Question

MongoDB Group by users having not performed event x

I have a events collection. I want users who did not perform event click.
Example -

collection -
{
'event' : 'open'
'user' : 1
},
{
'event' : 'open'
'user' : 2
},
{
'event' : 'click'
'user' : 2
}


I want result as following :

{ 'user' : 1 }


What i am getting is :

{ 'user' : 1 },
{ 'user' : 2 }


My Code :

$collection->aggregate(array(
array('$match' => array('$event' => array('$not' => 'click')) ),
array('$group' =>
array(
'_id' => '$user'
),
)
))

Answer

I should first group the documents and then filter the user who havent clicked and then project the result in your preferred format.

$collection->aggregate(array(
 array('$group' => 
              array(
                '_id' => '$user','events' => array('$push'=>'event')
              ),
     array('$match' =>  array('$events' => array('$not' => 'click')) ),
         array('$project' =>  array('user' => '$user') ),

))
Comments