Say i have a collection of answers where each answer contains an array of user_ids.
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
count() or db. mycollection.
To sort the whole array by value, or to sort by array elements that are not documents, identify the input array and specify 1 for an ascending sort or -1 for descending sort in the sortBy parameter.
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.
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.
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