Mongo equivalent of SQL's SELECT DISTINCT?

前端 未结 2 1520
一向
一向 2021-01-20 07:00

As per the title, what would be the PHP Mongo equivalent of something like this in SQL:

SELECT DISTINCT(field) FROM table WHERE someCondition = 1


        
相关标签:
2条回答
  • 2021-01-20 07:25

    Just issue a command and set the distinct key.

    Take a look at the following example from the docs:

    Finding all of the distinct values for a key.

    <?php
    
    $people = $db->people;
    
    $people->insert(array("name" => "Joe", "age" => 4));
    $people->insert(array("name" => "Sally", "age" => 22));
    $people->insert(array("name" => "Dave", "age" => 22));
    $people->insert(array("name" => "Molly", "age" => 87));
    
    $ages = $db->command(array("distinct" => "people", "key" => "age"));
    
    foreach ($ages['values'] as $age) {
        echo "$age\n";
    }
    
    ?>
    

    The above example will output something similar to:

    4
    22
    87
    
    0 讨论(0)
  • 2021-01-20 07:31

    If you need to add a where clause, use the following syntax:

    $ages = $db->command(array(
        "distinct" => "people", 
        "key" => "age",
        "query" => array("someField" => "someValue")));
    
    0 讨论(0)
提交回复
热议问题