29

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

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

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

它不适用于“4e49fd8269fd873c0a000000”前面的 MongoID 或 ObjectID 前缀。

在 PHP 中使用 mongoDB 查询 ObjectID 的正确方法是什么?

4

4 回答 4

58

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

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

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

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

于 2011-08-16T06:27:29.317 回答
28

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

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

根据菲尔的回答。

于 2016-03-24T22:14:21.107 回答
4

对于 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<br />";
}
于 2018-11-04T21:14:26.010 回答
1

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

$filter = [];
$filter['_id'] = (new \MongoId('4e49fd8269fd873c0a000000'))->toBSONType();
$cursor = $collection->find($filter);
于 2018-03-05T15:01:23.687 回答