Sorting by number of elements in array of the document in mongo [duplicate]
Say i have a collection of answers where each answer contains an array of user_ids.
- answer has_and_belongs_to_many: users
Is it possible to have a query that sorts by the number of user_ids?
Answer.all.desc(num_user_ids)
开发者_运维百科i can cache this number, but i am hoping i do not have to. i am using mongoid
This is probably a duplicate of this question: How can I sort MongoDB query results by inner array size?
To summarize: no, you can't sort by an array length as you wish, the recommendation is to store an additional field in the document that contains the number of users.
You could do this with MapReduce, though. But that would produce another table, which is probably not desired.
This is an old question, but it's the top result for "mongoid sort by array length" and it's no longer correct.
This query can be done with the Mongo collections framework as in this question.
When done in mongoid it looks something like this:
unwind = { '$unwind' => '$tags' }
group = { '$group' =>
{ '_id' => '$_id', 'tags' => { '$push' => '$tags' }, 'count' => { '$sum' => 1 } }
}
sort = { '$sort' => { 'count' => 1 } }
Photo.collection.aggregate([unwind, group, sort])
精彩评论