我有一组学生,每个学生的记录如下所示,我想按 score
的降序对 scores
数组进行排序。
这个咒语在 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
}
]
}
我正在尝试这个咒语......
doc = db.students.find()
for (_id,score) in doc.scores:
print _id,score
但它不起作用。
最佳答案
您需要在应用程序代码中操作嵌入数组或使用新的 Aggregation Framework在 MongoDB 2.2 中。
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
}
https://stackoverflow.com/questions/13449874/
相关文章:
javascript - 使用 MongoDB 更新嵌套数组
mongodb - 奇怪的 mongodb 和 mongoose 错误 : not master a
c# - MongoDB C# Driver 2.0 - 更新文档
javascript - Mongoose - RangeError : Maximum Call
mongodb - 在 MongoDB 中,如果删除了集合,索引也会自动删除吗?
mongodb - 如何知道mongodb使用的是哪个存储引擎?
java - $push 和 $set 在同一个 MongoDB 更新中