通过排序数据获取不同的值
我需要一个查询来获取根据 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"
}
我需要一个查询来对分数上的所有记录进行排序并返回不同的键......
I need a Query to get distinct keys with sorted on basis of score in 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.....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用聚合框架按您想要区分的元素进行分组(分组使其不同)。因此,如果您希望按分数排序,然后获取不同的键,您可以执行以下操作 - 按分数排序,按键分组并将分数添加为元素数组(已排序):
这将产生不同的键以及分数数组,其中是包含在具有重复键的文档中的那些分数。我不确定这正是您正在寻找的东西,我知道这是一个老问题,但我认为这可能会帮助其他人在未来查看它 - 作为执行此操作的另一种方式。
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):
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.
mongodb中有distinct命令:
你可以像这样使用distinct
:在关系数据库中相同:
并且通过添加以下代码来排序结果 :
总结果将是这样的:
There is distinct command in mongodb:
you can use distinct like this:
the same in relational database:
And than sort result by adding following code:
Total result will be like this:
使用 mongo shell v3.6.23,
您可以使用不同的值对数据进行排序,
您无法指定要对结果进行排序的字段,也无法定义顺序。
例如:你不能使用
.sort({key:value})
这里的原因是这里的 sort() 这里不是在游标上定义的 mongosh 排序。
distinct 查询返回 javascript 的 Array.prototype,因此您可以使用所有 实例方法
Using mongo shell v3.6.23
you can sort the data along with distinct values by using
you cant specify for which field you want to sort the result nor you can define the order.
eg: you cant use
.sort({key:value})
herethe reason is that here sort() here is not the mongosh sort which is defined on cursor.
the distinct query returns javascript's Array.prototype, so you can use all instance methods on it