Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 451
meow Avatar asked Sep 21 '11 03:09

meow


People also ask

How do I count the number of elements in an array in MongoDB?

count() or db. mycollection.

How do I sort an array in MongoDB aggregate?

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.

How do I sort numbers in MongoDB?

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.


1 Answers

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.

like image 92
dlaidlaw Avatar answered Sep 17 '22 05:09

dlaidlaw