问题
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