对 MongoDB 中的嵌入数组进行排序
问题:
如何对分数数组进行排序MongoDB 集合中的每个学生记录按降序排列分数?
问题:
考虑以下学生记录:
{ "_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 } ] }
尝试使用嵌入的 JavaScript 手动迭代分数数组mongo shell 会提示错误。
解决方案:
要对分数数组进行排序,请考虑以下 MongoDB 聚合框架管道:
db.students.aggregate( // Match the document (uses index if suitable) { $match: { _id: 1 }}, // Unwind scores array { $unwind: '$scores' }, // Filter to specific score type (optional) { $match: { 'scores.type': 'homework' }}, // Sort scores array { $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 中的嵌入数组进行排序?的详细内容。更多信息请关注PHP中文网其他相关文章!