当我将一些文档插入到集合中(没有 ObjectID)时,mongoDB 添加了自己的 ObjectID。
我想通过其唯一的 ObjectID 查询文档。
$db->collection_name->find(array('_id'=>'4e49fd8269fd873c0a000000')));
它不适用于“4e49fd8269fd873c0a000000”前面的 MongoID 或 ObjectID 前缀。
在 PHP 中使用 mongoDB 查询 ObjectID 的正确方法是什么?
当我将一些文档插入到集合中(没有 ObjectID)时,mongoDB 添加了自己的 ObjectID。
我想通过其唯一的 ObjectID 查询文档。
$db->collection_name->find(array('_id'=>'4e49fd8269fd873c0a000000')));
它不适用于“4e49fd8269fd873c0a000000”前面的 MongoID 或 ObjectID 前缀。
在 PHP 中使用 mongoDB 查询 ObjectID 的正确方法是什么?
我认为现在 API 更改为MongoDB\BSON\ObjectID,您也可以使用[]PHP 5.4+ 中的数组来表示,所以它应该是:
$item = $collection->findOne(['_id' => new MongoDB\BSON\ObjectID( idToken )]);
根据菲尔的回答。
对于 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 />";
}
使用alcaeus/mongo-php-adapter(在 php 7 下),需要转换\MongoId为 BSON 类型:
$filter = [];
$filter['_id'] = (new \MongoId('4e49fd8269fd873c0a000000'))->toBSONType();
$cursor = $collection->find($filter);