Projection query in MongoDB, PHP syntax?

What is the php syntax that will do the work that the next mongodb shell will do?

> db.SoManySins.find({},{"_id":0,"FactoryCapacity":1}) 
+4
source share
2 answers

The MongoDB PHP driver functions are called similar to their fellow shells, so in this case you will use MongoCollection :: find () . The PHP driver uses associative arrays to map fields to MongoDB queries.

Since the PHP documentation page MongoCollection::find() does not currently include a projection example, I added one for completeness:

 <?php $m = new MongoClient(); $db = $m->selectDB('test'); $collection = new MongoCollection($db, 'SoManySins'); // Search criteria $query = array(); // Projection (fields to include) $projection = array("_id" => false, "FactoryCapacity" => true); $cursor = $collection->find($query, $projection); foreach ($cursor as $doc) { var_dump($doc); } ?> 

For projection specification you can use 1/0 (include / exclude), as in mongo shell, or equivalent true / false constants.

It is well worth working with the Tutorial in the MongoDB PHP driver documentation, as well as viewing some of the archived presentations on the 10gen website.

+11
source

If you use the MongoDB driver in conjunction with the MongoDB PHP library

 require 'vendor/autoload.php'; // include Composer autoloader $client = new MongoDB\Client("mongodb://localhost:27017"); $result = $client->your_database_name->SoManySins->find(array(),array('projection' =>array('_id'=>FALSE,'FactoryCapacity' => TRUE))); foreach ($result as $entry){ echo "<pre>"; print_r($entry); echo "</pre>"; } 
+1
source

All Articles