Query With Projection In MongoDB, PHP Syntax?
Asked Answered
M

2

5

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

> db.SoManySins.find({},{"_id":0,"FactoryCapacity":1})
Markmarkdown answered 14/4, 2013 at 6:27 Comment(0)
I
20

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.

Impetrate answered 14/4, 2013 at 9:17 Comment(2)
Turned out it was the way the collection is made up, I was missing that. All the old documentation ( the stuff which shows up on page 2 and 3 + of a Google search? Oh yeah, useful. Hope it never goes away. ) Right, well with the example above, I got the script working in a very few minutes. Here's another feather AND a bead!Markmarkdown
Note: The new PHP extension mongodb has a different API from the old deprecated mongo PHP extension.Frankhouse
B
5

If you are using MongoDB driver conjunction with the MongoDB PHP library

require 'vendor/autoload.php'; // include Composer's 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>";
}
Bartram answered 16/3, 2018 at 14:21 Comment(1)
it should be mentioned first that I love this reply, but more importantly it now does not allow TRUE and FALSE values for Projections. can only be of one value type, Truthy or Falsy not both.'MongoDB\\Driver\\Exception\\CommandException: Projection cannot have a mix of inclusion and exclusionConstructionist

© 2022 - 2024 — McMap. All rights reserved.