Jibin Mathew
Jibin Mathew

Reputation: 5112

Using $lookup with php7 mongo driver manager?

How to use aggregate and $lookup with php 7 mongo driver manager.

How to convert the following mongo command to php

db.a.aggregate([{$lookup:{from:"b",localField:"business_id",foreignField:"_id",as:"contact"}}])

Also recommend good reference tutorials.

Upvotes: 0

Views: 1252

Answers (3)

Yogesh Nikam Patil
Yogesh Nikam Patil

Reputation: 1280

PHP7.2

MongoDB 4.2

I took reference from @Jibin Mathew' answer but I got some errors.

then I added

'cursor' => new stdClass,

this line in code.

Now it's working properly.

//mongo database join example
    public function test_join() {

        global $mng;
        global $dbname;


        $pipeline =  [['$lookup' => ["from" => "b","localField" => "business_id","foreignField" => "_id","as" => "contact"]]];

        $aggregate = new \MongoDB\Driver\Command([
           'aggregate' => 'a', 
           'cursor' => new stdClass,
           'pipeline' => $pipeline,
           ]);

        $cursor = $mng->executeCommand($dbname, $aggregate);
        return $cursor;

    }

Upvotes: 1

SimBioT
SimBioT

Reputation: 79

Try something like this:

$mongo->db->a->aggregate([ ['$lookup' => ['from' => 'b', 'localField' => 'business_id', 'foreignField' => '_id', 'as' => 'contact'] ] ]);

Upvotes: 1

Jibin Mathew
Jibin Mathew

Reputation: 5112

This code worked

$mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$command = new MongoDB\Driver\Command([
    'aggregate' => 'a',
    'pipeline' => [
        ['$lookup' => ["from" => "b","localField" => "business_id","foreignField" => "_id","as" => "contact"]],
    ],
]);
$cursor = $mng->executeCommand('test', $command);

Upvotes: 2

Related Questions