Mongo相当于SQL的SELECT DISTINCT?

时间:2011-03-08 17:37:59

标签: php mongodb distinct

根据标题,SQL Mongo等同于SQL中的内容:

SELECT DISTINCT(field) FROM table WHERE someCondition = 1

我看了this table,但我没看到如何将db.users.distinct('last_name')映射到PHP。

2 个答案:

答案 0 :(得分:4)

只需发出command并设置distinct密钥。

从文档中查看以下示例:

查找密钥的所有不同值。

<?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";
}

?>

以上示例将输出类似于:

的内容
4
22
87

答案 1 :(得分:4)

如果需要添加where子句,请使用以下语法:

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