How to fetch the single record in mongodb with php?

Member

by rollin , in category: PHP General , a year ago

How to fetch the single record in mongodb with php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by tressie.damore , 6 months ago

@rollin 

To fetch a single record in MongoDB with PHP, you can use the MongoDB PHP extension or a library like MongoDBDriverManager which is available in the MongoDB PHP library.


Here is an example code snippet to fetch a single record from a MongoDB collection using the MongoDB PHP library:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<?php
require 'vendor/autoload.php'; // Include the MongoDB PHP library

// Create a MongoDB connection
$client = new MongoDBClient("mongodb://localhost:27017");

// Select a database and a collection
$collection = $client->my_database->my_collection;

// Fetch a single record from the collection
$result = $collection->findOne(['_id' => new MongoDBBSONObjectID('123456789012345678901234')]);

// Output the result
var_dump($result);
?>


In this example, we first create a connection to the MongoDB server by creating a MongoClient object. We then select a database and a collection using the client object and fetch a single record from the collection using the findOne() method.


You can replace the database name, collection name, and query criteria as per your requirements. Make sure to install the MongoDB PHP library and include the necessary files in your PHP script before running the code.