Use the aggregation structure using the operator from MongoDB 2.6 and higher: $size
db.collection.aggregate([
{ "$project": {
"title": 1,
"author": 1,
"votes": 1,
"length": { "$size": "$votes" }
}},
{ "$sort": { "length": -1 } },
{ "$project": {
"title": 1,
"author": 1,
"votes": 1,
}}
])
Simple enough.
If you do not have version 2.6, you can do this a little more:
db.collection.aggregate([
{ "$unwind": "$votes" },
{ "$group": {
"_id": "$id",
"title": { "$first": "$title" },
"author": { "$first": "$author" },
"votes": { "$push": "$votes" },
"length": { "$sum": 1 }
}},
{ "$sort": { "length": -1 } },
{ "$project": {
"title": 1,
"author": 1,
"votes": 1,
}}
])
This is pretty much the case.
source
share