mongo join with regexp

21:38
we combine the result of more than one collections by using following concepts in mongo
  • aggregation
  • lookup
  • pipeline
we have two collections here
  • Test 
  • Transactions
             
so we want combine the two collection result set by using foreign key user_id and also filter product type books
<?php
//connection db
include("config.php");

$collection1= 'test';

$collection2= 'transactions';

$my_collection = $db->selectCollection($collection1);

//pipeline
$pipeline = array(


    //lookup
    array('$lookup' => array('from'=>$collection2,

                                'localField'=>'user_id',

                                'foreignField'=>'user_id',

                                'as'=>'Transactions')),

   array('$match'=>array('Transactions'=>['$ne' => []],'Transactions.product'=>['$regex'=>new MongoRegex("/^book/i")])),



    //limit
    array('$limit' => 10),

    //skip
    array('$skip' => 0)


 );

$cursor = $my_collection->aggregate($pipeline,array('cursor'=>array('batchSize'=>10000)));

echo '<pre>';
print_r($cursor['cursor']['firstBatch']);
echo '</pre>';

Output


No comments:

Powered by Blogger.