Reputation: 9034
I'm trying to return a single document from the database by it's ID. This is what I have right now.
$id = "5a30ff2c3afc720394000ac2";
$collection = (new \MongoDB\Client(DB_HOST))->DB->posts;
$post = $collection->findOne(['_id' => $id]);
findOne()
returns nothing while find()
seems to be working. MongoDB documentations mentions that it would not return anything if no document were to be found. However, the document does seem to be in my database.
I have also tried PHP MongoDB documentation example.
$post = $collection->findOne(['_id' => new \MongoId($id)]);
This returns a no class found error.
Upvotes: 0
Views: 701
Reputation: 342
Mongo by default stores _id as Object
Try this
$collection->findOne(['_id'=> new \MongoDB\BSON\ObjectId("$mongoId")]);
You are using MongoDB driver, but using Mongo driver object.
Upvotes: 2