How to query data from MongoDB using PHP?

Member

by addison , in category: PHP Databases , a year ago

How to query data from MongoDB using PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by darion , a year ago

@addison 

To query data from MongoDB using PHP, you can use the MongoDB PHP Library, which provides a set of classes and methods for working with MongoDB databases.


Here's an example of how to query data from MongoDB using PHP:

  1. Connect to the MongoDB server:
1
$client = new MongoDBClient("mongodb://localhost:27017");


  1. Select the database and collection you want to query:
1
$collection = $client->mydatabase->mycollection;


  1. Define the query parameters:
1
$query = ['age' => 25];


This query will search for documents where the "age" field equals 25.

  1. Execute the query:
1
$result = $collection->find($query);


This will return a cursor object that you can iterate over to retrieve the matching documents.

  1. Process the results:
1
2
3
4
5
foreach ($result as $document) {
    // Do something with each document
    echo $document['_id'] . "
";
}


In this example, we're just printing the _id field of each matching document.


Note that this is just a basic example, and there are many more options and features available in the MongoDB PHP Library. You can refer to the official documentation for more information and examples.