Search code examples
mongodbmongoosebulkphp-mongodb

Mongodb php searching using _id gives errors


I want to search _id by using executeQuery mongodb driver php.

Here is my document structure of the users collection

{
    "_id" : ObjectId("55ad0bd1032e1b12088b46a8"),
    "email" : "abc@abc.com"
}

And my php code is

<?php
//Getting object id
$id = new MongoId("55ad0bd1032e1b12088b46a8");
//filtering 
$filter = ['_id' =>$id];

$options = [];

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

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$cursor = $manager->executeQuery('db.users', $query);

when I run it I got following errors

PHP Fatal error: Uncaught exception 'MongoDB\Driver\Exception\ConnectionException' with message 'unknown operator: $id' in /test.php:27 Stack trace: 0 /test.php(27): MongoDB\Driver\Manager->executeQuery('db.users', Object(MongoDB\Driver\Query)) 1 {main} thrown in test.php on line 27

Any help?


Solution

  • As Per comment of @Felipe Sulser

    The line

    $id = new MongoId("55ad0bd1032e1b12088b46a8");
    

    should be

    $id = new MongoDB\BSON\ObjectId("55ad0bd1032e1b12088b46a8");
    

    Now it is working