Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sorting 使用排序数据获取不同的值_Sorting_Mongodb_Distinct Values - Fatal编程技术网

Sorting 使用排序数据获取不同的值

Sorting 使用排序数据获取不同的值,sorting,mongodb,distinct-values,Sorting,Mongodb,Distinct Values,在Mongodb 1.6.5中,我需要一个查询来获得根据分数排序的不同键 我有这样的记录 {key ="SAGAR" score =16 note ="test1" } {key ="VARPE" score =17 note ="test1" } {key ="SAGAR" score =16 note ="test2" } {key ="VARPE" score =17 note ="test2" } 我需要一个查询,对所有记录进行排序,并返回不同的键…..mongodb中有: 您可

在Mongodb 1.6.5中,我需要一个查询来获得根据分数排序的不同键

我有这样的记录

{key ="SAGAR"
score =16
note ="test1"
}

{key ="VARPE"
score =17
note ="test1"
}

{key ="SAGAR"
score =16
note ="test2"
}

{key ="VARPE"
score =17
note ="test2"
}
我需要一个查询,对所有记录进行排序,并返回不同的键…..

mongodb中有:

您可以像这样使用distinct:

db.test.distinct({"key":true,"score":true,"note":true}); 
 db.test.distinct({"key":true,"score":true,"note":true}).sort({score : 1}); 
在关系数据库中也是如此:

SELECT DISTINCT key,score,note FROM test; 
然后添加以下代码:

.sort({score : 1}) // 1 = asc, -1 = desc
总结果如下所示:

db.test.distinct({"key":true,"score":true,"note":true}); 
 db.test.distinct({"key":true,"score":true,"note":true}).sort({score : 1}); 

您可以使用聚合框架按要区分的元素进行分组(分组使其区分)。因此,如果您希望按分数排序,然后获得不同的键,您可以执行以下操作-按分数排序、按键分组并将分数添加为元素数组(已排序):


这将导致不同的键以及分数数组,这些分数包含在具有重复键的文档中。我不确定这是否正是您想要的,我知道这是一个老问题,但我认为这可能有助于其他人在将来查看它-作为一种替代方法。

因此,如果您对这组数据运行此查询,您希望得到什么样的结果(在询问查询问题时,始终显示最好的结果)您使用的编程语言是什么?@SagarVarpe-您接受的答案不再可行(聚合框架似乎是现在唯一的方法)。也许可以考虑改变你所接受的答案?在蒙戈V2.2+中,你可以做到:<代码> dB。代码>显然这不再可行(v3.8.0)-产生排序不能与distinct一起使用的错误。你能确认吗?排序不能与distinct一起使用这里有一个活动的功能请求,如果你有相同的问题,请投票支持它:我有MongoDB 3.0.7,对于1个字段它工作得很好:
db.collection.distinct(“date”).sort({date:1})
。MongoDB 3.2.5只需要一个字符串作为参数。$push是用于此目的的错误运算符。改为使用$addToSet。@user3072843据我所知,$addToSet按未排序的顺序添加项目,而$push按项目到达组的顺序添加,在本例中为排序顺序。