本文介绍了如何在MongoDB中的集合记录中对数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
MongoDB菜鸟在这里...
MongoDB noob here...
好吧,我有一组学生,每个学生的记录都如下所示....我想按降序对'type':'homework'分数进行排序.
Ok, I have a collection of students, each with a record that looks like the following.... I want to sort the 'type' : 'homework' scores in descending order.
在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
外壳中的示例聚合:
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中的集合记录中对数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!