Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query With Projection In MongoDB, PHP Syntax?

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

> db.SoManySins.find({},{"_id":0,"FactoryCapacity":1})
like image 451
MountainMan Avatar asked Apr 14 '13 06:04

MountainMan


People also ask

How do I add a projection in MongoDB query?

Build a To-Do List App with Node, Express, React and MongoDB. In MongoDB, projection means selecting only the necessary data rather than selecting whole of the data of a document. If a document has 5 fields and you need to show only 3, then select only 3 fields from them.

What is a projection in MongoDB queries?

What are projection queries? In MongoDB, the default for queries is to return all fields in matching documents. A projection query is used to specify or restrict the data returned in query results. By specifying a projection query, you can specify the fields you want to return or exclude.

Which of the following command is used for projection in MongoDB?

One can use projection with db. collection. find() method. In this method, the second parameter is the projection parameter, which is used to specify which fields are returned in the matching documents.


1 Answers

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.

like image 186
Stennie Avatar answered Oct 30 '22 17:10

Stennie