Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

160
Views
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 !

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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); 
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!