简体   繁体   English

MongoDB文档中的多个值可以使用PHP分别返回吗?

[英]Can multiple values from MongoDB doc be returned using PHP distinct?

Using MongoDB with PHP driver; 将MongoDB与PHP驱动程序配合使用;

For the purpose of the question, I have a simple Mongo collection and each doc has 4 rows. 为了这个问题,我有一个简单的Mongo集合,每个文档有4行。 I'd like to get the distinct username AND id when doing a query, while using a where clause based on the public value. 我想在进行查询时使用基于公共值的where子句来获取不同的用户名和ID。

my code for testing: 我的测试代码:

$m  = new Mongo;
$db = $m->selectDB("test");
$db->dropCollection("activities");
$collection = $db->activities;

$collection->insert(array("username" => "brady", "public" => "Y", "userId" => "1", "activity" => "blah"));
$collection->insert(array("username" => "scott", "public" => "Y", "userId" => "2", "activity" => "blah"));
$collection->insert(array("username" => "brady", "public" => "N", "userId" => "1", "activity" => "blah"));

$cursor = $db->command(array("distinct"=> "activities", "key" => "username", "query"=>array("public"=>"Y")));

var_dump($cursor['values']);

The dump produces: 转储产生:

array(2) { [0]=> string(5) "brady" [1]=> string(5) "scott" }

I want the username, but I also want the userId. 我需要用户名,但我也需要userId。 Could anyone help me figure out how to get both values from the doc while using distinct? 有人可以帮助我弄清楚如何在使用distinct的同时从文档中获取两个值吗?

You can't do this with distinct: http://docs.mongodb.org/manual/reference/command/distinct/ it only supports single keys. 您不能使用以下命令来做到这一点: http : //docs.mongodb.org/manual/reference/command/distinct/它仅支持单个键。

You can however achieve this with the aggregation framework. 但是,您可以使用聚合框架来实现。 It should be easy to translate this to PHP: 将其转换为PHP应该很容易:

db.activities.aggregate({ $match: { public: "Y" } },
    {
      $group: {
        _id: 1,
        names: { $addToSet: "$username" },
        ids: { $addToSet: "$userId" }
      }
    }
});

On your test data I get: 根据您的测试数据,我得到:

{
    "result" : [
        {
            "_id" : 1,
            "names" : [
                "scott",
                "brady"
            ],
            "ids" : [
                2,
                1
            ]
        }
    ],
    "ok" : 1
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM