30

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.

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

It does not work either with prefix of MongoID or ObjectID in front of '4e49fd8269fd873c0a000000'.

What is the proper way to query by ObjectID with mongoDB in PHP?

David Newcomb
  • 10,639
  • 3
  • 49
  • 62
jwchang
  • 10,584
  • 15
  • 58
  • 89

4 Answers4

57

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

Phil
  • 157,677
  • 23
  • 242
  • 245
  • I write same query, but query is not working. $collection = $db->Collection("video_detail"); $cursor = $collection->findOne(array('user_id' => new MongoId("575289f33a31b98a4c8b4567"))); – Jagdish Thakre Jun 08 '16 at 11:08
29

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
coolgod
  • 539
  • 6
  • 9
  • This works for me, but I am at a bit of a loss to understand where `MongoDB\BSON\ObjectID` comes from. It's not defined anywhere in the `vendor/mongodb` folder as a separate class, as far as I can see. NetBeans is normally good at project introspection, but it can't see it either. And yet it works! – halfer Sep 18 '17 at 23:29
  • Thanks you so much man. Really Appreciate. Your are Start for me. – Denis Bhojvani Nov 02 '17 at 10:17
  • For me new \MongoDB\BSON\ObjectID( idToken )] worked for me, notice the "\". Hope this helps someone. – Marc Alexander Jun 01 '20 at 05:01
4

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 />";
}
Roman
  • 19,236
  • 15
  • 93
  • 97
1

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);
glen
  • 1,657
  • 19
  • 19
  • with php 8 how to use a custom oid instead of the default mongodb one ? like "ABCD" php -version PHP 8.0.11 (cli) (built: Sep 23 2021 22:04:56) ( NTS ) Copyright (c) The PHP Group Zend Engine v4.0.11, Copyright (c) Zend Technologies with Zend OPcache v8.0.11, Copyright (c), by Zend Technologies # php --ri mongodb | grep version MongoDB extension version => 1.10.0 libbson bundled version => 1.18.0 libmongoc bundled version => 1.18.0 libmongocrypt bundled version => 1.2.1 – user3181125 Oct 07 '21 at 13:36
  • ERROR:MongoDB\Driver\Exception\InvalidArgumentException: Error parsing ObjectId string: 0F000001 – user3181125 Oct 07 '21 at 13:42