1

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 !

Dovre
  • 71
  • 1
  • 10

1 Answers1

2

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); 
s7vr
  • 73,656
  • 11
  • 106
  • 127
  • but how can we use aggregation with new php mongo db drivers – cpap May 29 '17 at 19:34
  • 1
    Np. You can find an example here. https://stackoverflow.com/questions/43029406/how-to-count-of-embedded-mongodb-php/43031072#43031072. Please consider creating a separate question if you have specific problem. – s7vr May 29 '17 at 19:36