Reputation: 75
There is a command line syntax in mongo that goes something like this
db.collection.find('nested_array.some_nested_key':'some_nested_value',{'nested_array.$' => 1})
This finds and returns just the "nested_array(s)" that match the criteria and not the entire object.
Problem is I can't seem to find the ".$" equivalent in the php driver. anyone have any ideas?
Upvotes: 1
Views: 64
Reputation: 103455
The methods in the MongoDB PHP driver are similar to their mongo shell counterparts, so the projection with the $ positional
operator also uses associative arrays to map fields to MongoDB queries. Something like this will produce the desired result:
<?php
$m = new MongoClient();
$db = $m->selectDB("test");
$collection = new MongoCollection($db, "collection_name");
// search for nested array
$fruitQuery = array("nested_array.some_nested_key" => "some_nested_value");
// projection (fields to include)
$projection = array("_id" => false, "nested_array.$" => true);
$cursor = $collection->find($query, $projection);
foreach ($cursor as $doc) {
var_dump($doc);
}
?>
Upvotes: 2