MongoDB select distinct and where

心不动则不痛 提交于 2021-02-20 10:17:23

问题


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

Can it be done in mongo?


回答1:


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.

Inserted following records into 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.

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"}
]



回答2:


Sure you can. No sure what db layer you are using, but in the native MongoDB driver it is possible

docs

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


来源:https://stackoverflow.com/questions/19294540/mongodb-select-distinct-and-where

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