Query With Projection In MongoDB, PHP Syntax?

MountainMan picture MountainMan · Apr 14, 2013 · Viewed 8.5k times · Source

What is the php syntax which will do the work which the following mongodb Shell does?

> db.SoManySins.find({},{"_id":0,"FactoryCapacity":1})

Answer

Stennie picture Stennie · Apr 14, 2013

The MongoDB PHP driver functions are named similar to their shell counterparts, so in this case you would be using MongoCollection::find(). The PHP driver uses associative arrays to map fields to MongoDB queries.

Since the PHP MongoCollection::find() documentation page doesn't currently include an example with projection, I've added one below 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 the projection spec you can use 1/0 (include/exclude) as in the mongo shell, or equivalent true/false constants.

It's well worth working through the Tutorial in the PHP MongoDB driver documentation as well as viewing some of the archived presentations on the 10gen web site.