How to fetch the single record in mongodb with php?

Member

by rollin , in category: PHP General , 2 years ago

How to fetch the single record in mongodb with php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by tressie.damore , a year 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.

Related Threads:

How to return multiple records from single record in oracle?
How to fetch record from database and send it to email using codeigniter?
How to fetch data of multiple users in one query in mongodb?
How to make a single page application with php?
How to fetch response from a callback url using php?
How to get column with duplicate record with php & mysql?