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

173
Views
Obtener objetos MongoDB\Driver\Cursor directamente en la clase especificada

Actualmente, cada documento obtenido de Mongo DB va a un objeto stdClass . Me gustaría cargar esto directamente en mi propia clase personalizada.

La clase

 class TestClass { private $id; private $class; function __construct($id, $name) { $this->id = $id; $this->class = $class; } }

El código

 $m = MongoDB\Driver\Manager('mongodb://<user>:<pass>@<host>/<db>'); $query = MongoDB\Driver\Query(['name' => 'TestFirst']); // I tried adding the following line, but it says that the constructor args are missing. // If I omit it, it just adds each cursor object as an instance of stdClass $opt = ['cursor' => new TestClass]; $results = $m->executeQuery('newDb.testCollection', $query, $opt); foreach ($results as $document) { var_dump($document); }

¿Es posible lo que quiero lograr, o necesito pasar por cada objeto stdClass y convertirlo en una instancia de TestClass ?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

La clase en sí necesita implementar la interfaz MongoDB\BSON\Unserializable y el bsonUnserialize(array $data) para convertir una matriz de datos BSON en la clase en cuestión.

 class TestClass implements MongoDB\BSON\Unserializable, MongoDB\BSON\Serializable { private $id; private $name; function __construct ($id, $name) { $this->id = $id; $this->name = $name; } function bsonUnserialize(array $data) { // This will be called *instead* of the constructor if unserializing $this->id = $data['_id']; $this->id = $data['name']; } }

El mapa de tipos de MongoDB\Driver\Cursor que se devuelve de la consulta debe configurarse para asignar un documento a una instancia de la clase personalizada. El código terminado se ve así.

 $mongo = new MongoDB\Driver\Manager($constr); $query = MongoDB\Driver\Query(['name' => 'TestFirst']); $cursor = $mongo->executeQuery($query); $cursor->setTypeMap('root' => 'array', 'document' => 'TestClass', 'array' => 'array'); foreach ($cursor as $doc) { var_dump($doc); }
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!