5

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?

sawa
  • 165,429
  • 45
  • 277
  • 381
tsinik
  • 503
  • 5
  • 11

3 Answers3

4

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.

Andrew Orsich
  • 52,935
  • 16
  • 139
  • 134
  • Thanks Andrew, but this is not what i'm looking for. I use Morphia as a POJO mapper, so i don't want to add irrelevant fields. in any way all javascript arrays have a length property. I'm wondering if there is a way to use it in a query. – tsinik Apr 23 '11 at 21:18
  • 1
    No, there is no way to do that; there is no support for sorting by a function nor is there a synthetic field which is the array length. That means for now you need to store a count if you want to embed it and sort on that. Be careful how you update it though. – Scott Hernandez Apr 24 '11 at 01:45
3

OK I found it :-)

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

Brent Worden
  • 10,624
  • 7
  • 52
  • 57
tsinik
  • 503
  • 5
  • 11
  • 3
    I'm pretty sure this query doesn't actually work. It may execute without giving an error, but when I try something similar in the mongo shell, nothing is actually sorted. – AlbertEngelB Apr 09 '14 at 13:28
0

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}}])
shou
  • 1