Use a estrutura de agregação com a ajuda do
$size
operador do MongoDB 2.6 e superior:db.collection.aggregate([
// Project with an array length
{ "$project": {
"title": 1,
"author": 1,
"votes": 1,
"length": { "$size": "$votes" }
}},
// Sort on the "length"
{ "$sort": { "length": -1 } },
// Project if you really want
{ "$project": {
"title": 1,
"author": 1,
"votes": 1,
}}
])
Simples o suficiente.
Se você não tem uma versão 2.6 disponível ainda pode fazer isso com um pouco mais de trabalho:
db.collection.aggregate([
// unwind the array
{ "$unwind": "$votes" },
// Group back
{ "$group": {
"_id": "$id",
"title": { "$first": "$title" },
"author": { "$first": "$author" },
"votes": { "$push": "$votes" },
"length": { "$sum": 1 }
}},
// Sort again
{ "$sort": { "length": -1 } },
// Project if you want to
{ "$project": {
"title": 1,
"author": 1,
"votes": 1,
}}
])
É bem isso.