I have to convert this query from mysql to mongoDB using php
select content_id ,member_id, content_type_id,social_network_id from recent_activty where content_type_id = 10 AND social_network_id = 9 order by id desc group by content_id limit 5
I need the result like :
array(2) {
["content_id"]=>
string(6) "122558"
["member_id"]=>
string(6) "180306",
["content_type_id"]=>
string(6) "10",
["social_network_id"]=>
string(6) "9",
},
array(2) {
["content_id"]=>
string(6) "122549"
["member_id"]=>
string(6) "180306",
["content_type_id"]=>
string(6) "10",
["social_network_id"]=>
string(6) "9",
},
array(2) {
["content_id"]=>
string(6) "122528"
["member_id"]=>
string(6) "180306",
["content_type_id"]=>
string(6) "10",
["social_network_id"]=>
string(6) "9",
},
I tried Aggregation Framework as
$result = $collection->aggregate(array(
'$match' => array('content_type_id'=>"10", "social_network_id"=>"9"),
'$project' => array('content_type_id'=>1, "social_network_id"=>1, "content_id"=>1),
'$group' => array('_id' => array('member_id'=>'$member_id')),
'$sort' => array('_id'=>-1),
'$limit' => 5,
));
But i got this error
["errmsg"]=>
string(80) "exception: A pipeline stage specification object must contain exactly one field."
and I tried
$result = $collection->aggregate(array(
'$match' => array('content_type_id'=>"10", "social_network_id"=>"9"),
'$project' => array("_id"=>'$content_id' ,'content_type_id'=>1),
'$group' => array('_id' => array('content_id'=>'$content_id', 'member_id'=>'$member_id')),
)
);
I'm new to mongoDB AND I spent a lot of time to convert this query and to solve this error , any one can help me
Thanks
You can use querymongo.com to convert mysql queries to mongo. For this question your code should be like this.
$result = $collection->aggregate(array(
array(
'$match' => array('content_type_id'=>"10", "social_network_id"=>"9"
)),
array(
'$project' => array("_id"=>'$content_id' ,'content_type_id'=>1
)),
array(
'$group' => array('_id' => array('content_id'=>'$content_id', 'member_id'=>'$member_id'))),
)
);
$match , $group (pipeline operators) should be inside array. http://php.net/mongocollection.aggregate
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With