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
.
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
but it's not working.
To sort documents in MongoDB, you need to use sort() method. The method accepts a document containing a list of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.
Filter MongoDB Array Element Using $Filter Operator This operator uses three variables: input – This represents the array that we want to extract. cond – This represents the set of conditions that must be met. as – This optional field contains a name for the variable that represent each element of the input array.
yep MongoDB keeps the order of the array.. just like Javascript engines..
you can use mongodb aggregation stage $addFields which will add extra field to store count and then followed by $sort stage. Show activity on this post. You can use $size attribute to order by array length.
You will need to manipulate the embedded array in your application code or using the new Aggregation Framework in MongoDB 2.2.
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 }} )
Sample output:
{ "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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With