Find a document with ObjectID in mongoDB

前端 未结 4 1662
暗喜
暗喜 2020-12-13 09:32

When I inserted some documents into a collection (without an ObjectID) mongoDB adds its own ObjectIDs.

I want to query a document by its unique ObjectID.

<         


        
相关标签:
4条回答
  • 2020-12-13 09:55

    With alcaeus/mongo-php-adapter (under php 7), needed to convert \MongoId to BSON type:

    $filter = [];
    $filter['_id'] = (new \MongoId('4e49fd8269fd873c0a000000'))->toBSONType();
    $cursor = $collection->find($filter);
    
    0 讨论(0)
  • 2020-12-13 09:57

    I think now the API changes to MongoDB\BSON\ObjectID, also you can use [] to denote an array in PHP 5.4+, so it should be:

    $item = $collection->findOne(['_id' => new MongoDB\BSON\ObjectID( idToken )]);
    

    based on Phil's answer.

    0 讨论(0)
  • 2020-12-13 10:02

    For MongoDB\Driver\Manager, a modern version of a MongoDB, you might consider the following working code:

    try {
      $DB_CONNECTION_STRING="mongodb://YourCredentials";
      require '../../vendor/autoload.php';
      $manager = new MongoDB\Driver\Manager( $DB_CONNECTION_STRING );
    
      $filter = ['_id' => new MongoDB\BSON\ObjectID( '5bdf54e6d722dc000f0aa6c2' )];
      $options = [];
    
      $query = new MongoDB\Driver\Query($filter, $options);     
      $docs = $manager->executeQuery('YourDbName.YourCollectionName', $query);
    }
    catch (MongoDB\Driver\Exception\Exception $e) { 
      $filename = basename(__FILE__); 
      echo "The $filename script has experienced an error.\n"; 
      echo "It failed with the following exception:\n"; 
      echo "Exception:", $e->getMessage(), "\n"; 
    } 
    

    For testing purposes:

    foreach ($docs as $doc) {
      print_r($doc);
      //or you can: echo "$doc->item  $row->qty  $row->status<br />";
    }
    
    0 讨论(0)
  • 2020-12-13 10:12

    Pretty sure you have to use a MongoId object, eg

    $item = $collection->findOne(array(
        '_id' => new MongoId('4e49fd8269fd873c0a000000')));
    

    The notes on the Querying page are a little obtuse but it does mention...

    Unless the user has specified otherwise, the _id field is a MongoId. The most common mistake is attepting to use a string to match a MongoId. Keep in mind that these are two different datatypes, and will not match each other in the same way that the string "array()" is not the same as an empty array

    0 讨论(0)
提交回复
热议问题