简体   繁体   English

MongoDB选择distinct和where

[英]MongoDB select distinct and where

So I'm doing a select distinct which works, but I also want to add another key. 所以我正在做一个有效的选择,但我也想添加另一个键。

$data = $this->db->command(array("distinct" => "scores","key"=>"target_user"));

I need something like this: SELECT DISTINCT target_user FROM scores where seen = 1 我需要这样的东西: SELECT DISTINCT target_user FROM scores where seen = 1

Can it be done in mongo? 可以在mongo中完成吗?

You can do it as follows by using distinct query : 您可以使用不同的查询执行以下操作:

db.scores.distinct("target_user", {"seen":1})

Running distinct query using Aggregate Framework is shown below. 使用Aggregate Framework运行不同的查询如下所示。

Inserted following records into MongoDB. 将以下记录插入MongoDB。

db.scores.insert({target_user:"a",seen:1, name:"name1"})
db.scores.insert({target_user:"a",seen:0, name:"name1"})
db.scores.insert({target_user:"b",seen:1, name:"name2"})
db.scores.insert({target_user:"c",seen:1, name:"name3"})
db.scores.insert({target_user:"d",seen:0, name:"name4"})

Then by running the following aggregate query you can find the distinct target_user's where seen = 1. Note that it will also return name field. 然后通过运行以下聚合查询,您可以找到不同的target_user,其中see = 1.请注意,它也将返回name字段。

db.scores.aggregate(
{$match:{seen:1}},
{$group: {_id : "$target_user", name: {$first:"$name"}}},
{$group : {_id : "$_id", name: {$first:"$name"}}}
);

Then result will be as follows : 然后结果如下:

"result" : [
    {"_id" : "a","name" : "name1"},
    {"_id" : "b","name" : "name2"},
    {"_id" : "c","name" : "name3"}
]

Sure you can. 你当然可以。 No sure what db layer you are using, but in the native MongoDB driver it is possible 不确定您使用的是哪个数据库层,但在本机MongoDB驱动程序中是可行的

docs 文档

$mongoCollection->distinct("target_user", ['seen' => 1]);

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

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