1

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?

1 Answer 1

2

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);
    }
?>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.