MongoDB
 SQL >> Datenbank >  >> NoSQL >> MongoDB

Ein Array innerhalb eines MongoDB-Collection-Dokuments sortieren

Um ein eingebettetes Array umzusortieren, manipulieren Sie es entweder in Ihrem Anwendungscode oder greifen zum Aggregation Framework, das seit MongoDB 2.2 verfügbar ist. Die Stufen $unwind und $sort des Frameworks erlauben Ihnen dies direkt in der 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 }} ) 

Das Ergebnis ist ein Strom von Dokumenten, geordnet nach Punktzahl:

{ "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 } 

Da $unwind das Array in einzelne Dokumente auffächert, erhalten Sie einen Ausgabedatensatz pro Element, jeweils mit der sortierten Punktzahl.