Dovre
Dovre

Reputation: 71

Use aggregate method with the new MongoDB driver classes in PHP

I am new with mongo.

I try to get a subDocument of a document, here is my document :

{
    "_id" : ObjectId("5900ab35c720b210c000032c"),
    "name" : "B 1",
    "providers" : [ 
        {
            "id" : ObjectId("59030550c720b211dc005e9e"),
            "name" : "F 1"
        }, 
        {
            "id" : ObjectId("59030577c720b211dc005e9f"),
            "name" : "F 2"
        }
    ]
}

and I want to get this subDocument :

{
    "id" : ObjectId("59030577c720b211dc005e9f"),
    "name" : "F 2"
}

I think I need to use these class : http://php.net/manual/en/mongocollection.aggregate.php but I didn't manage to use it with my manager instance of the class : http://php.net/manual/en/class.mongodb-driver-manager.php.

The PHP Manual do not show how to use it with the new Driver.

Can someone help me?

Thank you and Good Day !

Upvotes: 1

Views: 1730

Answers (1)

s7vr
s7vr

Reputation: 75934

You don't have to use aggregation for the task.

You can use regular queries for selecting the first matching sub document in the embedded arrays.

You can approach it in a couple of ways.

$Positional Projection

$filter = ['_id' => new MongoDB\BSON\ObjectID("5900ab35c720b210c000032c"), 'providers.id' => new MongoDB\BSON\ObjectID("59030577c720b211dc005e9f") ];

$options = ['projection' => ['_id' => 0, 'providers.$' => 1],];

$elemMatch Projection

$filter = ['_id' => new MongoDB\BSON\ObjectID("5900ab35c720b210c000032c")];

$options = [
        'projection' => ['_id' => 0, 'providers' => ['$elemMatch'=> ['id' => new MongoDB\BSON\ObjectID("59030577c720b211dc005e9f")]]],
    ];

You'll use the executeQuery to run regular queries.

$query = new \MongoDB\Driver\Query($filter, $options);

$cursor = $manager->executeQuery(dbName.collectionName, $query); 

Upvotes: 2

Related Questions