mongodb 使用排序数据获取不同的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4759437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get Distinct Values with Sorted Data
提问by Sagar Varpe
I need a Query to get distinct keys with sorted on basis of score in Mongodb 1.6.5
我需要一个查询来获取不同的键,并根据 Mongodb 1.6.5 中的分数进行排序
I have records Like
我有记录喜欢
{key ="SAGAR"
score =16
note ="test1"
}
{key ="VARPE"
score =17
note ="test1"
}
{key ="SAGAR"
score =16
note ="test2"
}
{key ="VARPE"
score =17
note ="test2"
}
I need a query which sorts all records on score and returns me distinct key.....
我需要一个查询来对所有记录进行排序并返回不同的键.....
采纳答案by Andrew Orsich
There is distinct commandin mongodb:
mongodb 中有不同的命令:
you can use distinct like this:
你可以像这样使用不同的:
db.test.distinct({"key":true,"score":true,"note":true});
the same in relational database:
在关系数据库中相同:
SELECT DISTINCT key,score,note FROM test;
And than sort resultby adding following code:
.sort({score : 1}) // 1 = asc, -1 = desc
Total result will be like this:
总结果将是这样的:
db.test.distinct({"key":true,"score":true,"note":true}).sort({score : 1});
回答by Stuart
You can use the aggregation framework to group by the element you want to be distinct (group makes it distinct). So if you wish to sort on score then get distinct keys you could do the following - sort by score, group by key and add score as arrays of elements (already sorted):
您可以使用聚合框架按要区分的元素进行分组(组使其区分)。因此,如果您希望按分数排序然后获得不同的键,您可以执行以下操作 - 按分数排序、按键分组并将分数添加为元素数组(已排序):
db.test.aggregate([
{ $sort : { score : -1 } },
{ $group : {_id : "$key", scores : { $push : "$score" } } }
])
This will result in distinct keys along with an array of scores which are those scores contained in the documents with duplicate keys. I'm not sure this is exactly what you're looking for and I know this is an old question but I thought this might help out someone else looking at it in the future - as an alternative way of doing this.
这将导致不同的键以及一组分数,这些分数是包含在具有重复键的文档中的分数。我不确定这正是你要找的,我知道这是一个老问题,但我认为这可能会帮助其他人在未来看到它 - 作为这样做的另一种方式。