Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

162
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda