How can I sort MongoDB query results by size of internal array?

I am using Morphia to access mongoDB. I need to get a list of objects by the length of the internal array. Does anyone have any ideas how to do this without getting the whole collection in Java and not sorting it there?

+4
source share
3 answers

OK I found :-)

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

+3
source

You must create an additional field with the size of the nested array and use $ inc to update this field.

You can also use $ where , but it is very slow.

You view the length of the nested array as follows:

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

But, as I said, it’s better to create an extra field.

+4
source

eg:

tmb_results_by_tissue_other raw data:

 {"base_info":[1,2,3],"type":"123"}, {"base_info":[2,3,4,5],"type":"123"}, 

in aggregate

 db.tmb_results_by_tissue_other.aggregate([{$project:{"type":1, num:{$size:"$base_info"}}},{$sort:{"num":-1}}]) 
0
source

All Articles