Query With Projection In MongoDB, PHP Syntax?

自作多情 提交于 2019-11-30 15:51:59

问题


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

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

回答1:


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.




回答2:


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>";
}


来源:https://stackoverflow.com/questions/15996394/query-with-projection-in-mongodb-php-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!