How to sort array inside collection record in MongoDB?(如何在 MongoDB 中对集合记录中的数组进行排序?)
问题描述
我有一组学生,每个学生的记录如下所示,我想按 score
的降序对 scores
数组进行排序.
I have a collection of students, each with a record that looks like the following and I want to sort the scores
array in descending order of score
.
这个咒语在 mongo shell 上是什么样子的?
what does that incantation look like on the mongo shell?
> db.students.find({'_id': 1}).pretty()
{
"_id" : 1,
"name" : "Aurelia Menendez",
"scores" : [
{
"type" : "exam",
"score" : 60.06045071030959
},
{
"type" : "quiz",
"score" : 52.79790691903873
},
{
"type" : "homework",
"score" : 71.76133439165544
},
{
"type" : "homework",
"score" : 34.85718117893772
}
]
}
我正在尝试这个咒语......
I'm trying this incantation....
doc = db.students.find()
for (_id,score) in doc.scores:
print _id,score
但它不起作用.
推荐答案
您将需要在应用程序代码中操作嵌入数组或使用新的 聚合框架.
You will need to manipulate the embedded array in your application code or using the new Aggregation Framework in MongoDB 2.2.
mongo
shell 中的示例聚合:
Example aggregation in the mongo
shell:
db.students.aggregate(
// Initial document match (uses index, if a suitable one is available)
{ $match: {
_id : 1
}},
// Expand the scores array into a stream of documents
{ $unwind: '$scores' },
// Filter to 'homework' scores
{ $match: {
'scores.type': 'homework'
}},
// Sort in descending order
{ $sort: {
'scores.score': -1
}}
)
样本输出:
{
"result" : [
{
"_id" : 1,
"name" : "Aurelia Menendez",
"scores" : {
"type" : "homework",
"score" : 71.76133439165544
}
},
{
"_id" : 1,
"name" : "Aurelia Menendez",
"scores" : {
"type" : "homework",
"score" : 34.85718117893772
}
}
],
"ok" : 1
}
这篇关于如何在 MongoDB 中对集合记录中的数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 MongoDB 中对集合记录中的数组进行排序?


基础教程推荐
- 我什么时候应该在导入时使用方括号 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 动态更新多个选择框 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01