Using Joins in mongo db with php

22:42
we can easily combine one or more documents result set based on foreign key relation in mongo so please follow below procedure to achieve this. we are using following concepts to join documents in mongo
  • Aggregate
  • pipeline
  • lookup

Mongo Connection


create config.php to establish connection with mongo
<?php 
$dbhost = 'localhost';
$m = new Mongo("mongodb://$dbhost:27017");  
$db = $manager->selectDB("mydba");  
?>

Aggregate

This match operation performs only in collection1 ('test') not in collection 2 ('transactions'). if you want perform match in both collections then follow below Link. Match and lookup in mongo collection2 (transactions) documents are empty that result set is also showing in results. so if you want non empty trasactions then add
"Transactions" => [ '$ne' => [] ]
in match array and this is worked only when you are placed after lookup.
<?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')),
    

                                //match
     array('$match' => array('age'=>'25','Transactions' => array('$ne'=>[]))),
    
    //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:



Array
(
    [0] => Array
        (
            [_id] => MongoId Object
                (
                    [$id] => 5b20e0ba33e06a192c323fe7
                )

            [user_id] => 1
            [name] => sekhar
            [age] => 25
            [state] => AP
            [country] => India
            [Transactions] => Array
                (
                    [0] => Array
                        (
                            [_id] => MongoId Object
                                (
                                    [$id] => 5b20f50933e06a192c323feb
                                )

                            [user_id] => 1
                            [amount] => 20
                            [quantity] => 1
                            [product] => Book1
                        )

                    [1] => Array
                        (
                            [_id] => MongoId Object
                                (
                                    [$id] => 5b20f59033e06a192c323fed
                                )

                            [user_id] => 1
                            [amount] => 23
                            [quantity] => 1
                            [product] => Book3
                        )

                )

        )
);
 

No comments:

Powered by Blogger.