Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort MongoDB query results by inner array size?

I'm using Morphia to access mongoDB. I need to get a list of objects by the length of the inner array. Does any one have an idea how it can be done without getting all the collection to Java and sort it there?

like image 381
tsinik Avatar asked Apr 23 '11 17:04

tsinik


People also ask

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.

Can we sort data in MongoDB?

MongoDB can perform sort operations on a single-field index in ascending or descending order. In compound indexes, the sort order determines whether the index can be sorted. The sort keys must be listed in the same order as defined in the index.


2 Answers

You should create extra field with nested array size and use $inc to update this field.

Also you can use $where , but it very slow.

You search by nested array length like this:

db.coll.find({ $where: "this.nestedArray.length > 3" });

But as i said better to create an extra field.

like image 133
Andrew Orsich Avatar answered Oct 11 '22 07:10

Andrew Orsich


OK I found it :-)

dataStore.find(MyClass.class).order("-inner_array.length").asList();
does the trick.

like image 34
tsinik Avatar answered Oct 11 '22 08:10

tsinik