How to project data in MongoDB using PHP?

by dalton_moen , in category: PHP Databases , 2 years ago

How to project data in MongoDB using PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by hal.littel , 2 years ago

@dalton_moen 

To project data in MongoDB using PHP, you need to use the MongoDBDriverQuery class along with the MongoDBDriverManager class. Here are the steps:

  1. Create a connection to the MongoDB server using the Manager class:
1
$manager = new MongoDBDriverManager("mongodb://localhost:27017");


  1. Create a Query object with the projection parameter:
1
2
3
4
$query = new MongoDBDriverQuery(
    [], // criteria
    ['projection' => ['name' => 1, 'email' => 1]] // projection
);


In this example, we are projecting only the name and email fields.

  1. Execute the query:
1
$result = $manager->executeQuery('mydatabase.mycollection', $query);


Note that mydatabase and mycollection should be replaced with your own database and collection names.

  1. Iterate through the result set and print the data:
1
2
3
foreach ($result as $document) {
    echo $document->name . ': ' . $document->email . '';
}


This will print the name and email of each document in the result set.


Overall, projecting data in MongoDB using PHP is a straightforward process with the Query and Manager classes.