Mongo equivalent of SQL's SELECT DISTINCT?

牧云@^-^@ 提交于 2019-12-20 02:11:15

问题


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

I've read looked at this table but I don't see how to map db.users.distinct('last_name') into PHP.


回答1:


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



回答2:


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

$ages = $db->command(array(
    "distinct" => "people", 
    "key" => "age",
    "query" => array("someField" => "someValue")));


来源:https://stackoverflow.com/questions/5236160/mongo-equivalent-of-sqls-select-distinct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!