首页 文章

在mongoDB中查找具有ObjectID的文档

提问于
浏览
23

当我将一些文档插入集合(没有ObjectID)时,mongoDB添加了自己的ObjectID .

我想通过其唯一的ObjectID查询文档 .

$db->collection_name->find(array('_id'=>'4e49fd8269fd873c0a000000')));

它不能用于'4e49fd8269fd873c0a000000'前面的MongoID前缀或ObjectID .

使用PHP中的mongoDB通过ObjectID进行查询的正确方法是什么?

4 回答

  • 0

    很确定你必须使用MongoId对象,例如

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

    Querying页面上的注释有点迟钝,但确实提到了......

    除非用户另有指定,否则_id字段是MongoId . 最常见的错误是考虑使用字符串来匹配MongoId . 请记住,这些是两种不同的数据类型,并且不会以字符串“array()”与空数组不同的方式相互匹配

  • 55

    我认为现在API更改为 MongoDB\BSON\ObjectID ,您也可以使用 [] 来表示PHP 5.4中的数组,因此它应该是:

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

    根据菲尔的回答 .

  • 14

    使用alcaeus/mongo-php-adapter(在php 7下),需要将 \MongoId 转换为BSON类型:

    $filter = [];
    $filter['_id'] = (new \MongoId('4e49fd8269fd873c0a000000'))->toBSONType();
    $cursor = $collection->find($filter);
    
  • 0

    对于MongoDB \ Driver \ Manager,MongoDB的现代版本,您可以考虑以下工作代码:

    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"; 
    }
    

    用于测试目的:

    foreach ($docs as $doc) {
      print_r($doc);
      //or you can: echo "$doc->item  $row->qty  $row->status
    "; }

相关问题