0

I want to retrieve all the values of the field color. How do php handle this values?

{
    _id : 1,

    color : ["red","blue","yellow"]
},
{
    _id : 2,

    color : ["green","black","grey"]
}

PHP code :

<?php

    $connect = new MongoClient();

    $collection = $database->database_name->collection;

    $cursor = $collection->find( array(), array( 'color' ) );

    foreach( $cursor as $val )

     echo json_encode( $val );

?>

As a result it does not return any values. How do I get the array values?

1 Answer 1

1

Use distinct to get distinct values of your array :

$cursor = $collection->distinct('color');

A full example :

<?php

    $m = new MongoClient();
    $db = $m->selectDB("testDB");
    $cursor = $db->users->distinct('color');
    var_dump($cursor);

?>
Sign up to request clarification or add additional context in comments.

3 Comments

the values are returned as a single value, I want the values to be returned as an array.
Do you mean like ["red","blue","yellow"],["green","black","grey"] ?
Ok! got it, resolved. Your code worked. Ignore the previous comment. Thanks.

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.