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

跟風遠走 提交于 2019-12-21 17:57:02

问题


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?


回答1:


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.




回答2:


OK I found it :-)

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




回答3:


for example:

source data tmb_results_by_tissue_other:

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

by aggregate

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


来源:https://stackoverflow.com/questions/5765858/how-can-i-sort-mongodb-query-results-by-inner-array-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!